Some basics of Zend Framework, I am documenting in case I forget these in the future 😉
Session Handling
1 2 3 |
$this->session = new Zend_Session_Namespace('user'); $this->session->key = "value"; echo $this->session->key; |
URL Routing
Add in Bootstrap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
public function _initRoutes() { // get the router $router = Zend_Controller_Front::getInstance()->getRouter(); $routeCategories = new Zend_Controller_Router_Route( 'index/cat/:id/', array( 'controller' => 'index', 'module' => 'default', 'action' => 'cat', 'id' => '') ); $routeSubCategories = new Zend_Controller_Router_Route( 'index/sub-cat/:id/', array( 'controller' => 'index', 'module' => 'default', 'action' => 'sub-cat', 'id' => '') ); $routeEntries = new Zend_Controller_Router_Route( 'index/entries/:id/', array( 'controller' => 'index', 'module' => 'default', 'action' => 'entries', 'id' => '') ); // add this route to the front controller $router->addRoute('category', $routeCategories); $router->addRoute('sub-cat', $routeSubCategories); $router->addRoute('entries', $routeEntries); } |
URL Helper
URL Helper is available via the method – url() in a view object. The method takes an array of options as its first parameter. The second parameter is optional where you can pass a route object name (eg. ‘category’ from the above url routing example). This comes in handy when you want to construct routed URLs.
By default the helper takes the following options: “action”, “controller” and “module”. If anyone of them is not provided, default one is used. It can also take in GET params which will be appended to the URL in a SEO friendly manner. If you pass a route object, you can simply pass the dynamic parts, no need to pass the entire action, controller or anything.
1 2 3 4 |
<?php echo $this->url(array("id"=>23),'category');?> // Outputs: '/index/cat/23' echo $this->url(array("id"=>23,"action"=>"cat","controller"=>"index")); // Outputs: '/index/cat/id/23' ?> |
Note that: In the second case, “id” itself is passed to the URL. But in the first case, the URL routing rule has been honored.
Inside a view script, you can directly use:
1 |
$this->url(); |
Since it is a member of the View object, you can also access it from an action like this:
1 |
$this->view->url(); |
Handling Redirection
Zend has a Redirector helper which provides advanced features when it comes to redirections. But for most cases, the built in _redirect() method of an action will do the job if used wisely with the URL helper.
1 2 3 4 5 |
$this->_redirect( $this->view->url( array( "action" => "login" ))); |
That’s it! Zend Framework is verbose and usually has more than one way to achieve something. It’s up to you to decide what suits your needs!