Zend Controller Action with Named Parameters

NOTE: The following code is taken directly from Zend Developer Zone, as posted and described by NirTayeb and some of the comments on that page. Refer to the original source for a full explanation of how it works and to thank the original author. I am only re-posting here to make it more accessible.
-------------------------------------------------------------------------------------------
Say you have a url like the following:

  • http://domain.com/products/view-product/product_id/15
If you're using the Zend Framework, the default interpretation of this URL is as follows:
  • no named module, so assume the default module
  • products must be the controller, so look for a ProductsController class
  • view-product must be the action, so look for a method called viewProductAction() in the ProductsController class
  • execute the viewProductAction(), then try to run the corresponding views/scripts/products/view-product.phtml script
To access the product_id in your viewProductAction() method, you typically do something like:
  • $product_id = $this->getRequest()->getParam('product_id');
While there's nothing wrong with this, it would be cleaner if you could define your action method with a named parameter and automatically have it available as follows:
  • public function viewProductAction($product_id) {
    • //$product_id now contains the value of 15, which is automatically passed in from the url
  • }
The advantage of this is less code, and more readable code. Also, notice that this is a required parameter now, so if the URL does not contain a product_id segment, an error should be thrown about the missing parameter. This is good, free error-checking.

This functionality can be easily implemented as follows:
  1. Download ParamControllerAction.php, and put it somewhere in your path.
  2. In your ProductController.php or any other controller, modify the class definition so it extends ParamControllerAction instead of the default Zend_Controller_Action
  3. Add required/optional parameters to all your Action methods, and use them like regular php code.
Some extra nice features of this code:
  • any named parameter also gets automatically added to the view. That is, if you have an action parameter $product_id, it will also be set as $this->view->product_id.
  • you can define optional parameters with default values, which act just like regular php code
  • the parameters in the URL do not have to be in the correct order, any order will do, the code matches parameters by name, not sequence

Comments

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word