I am building my first Zend Framework application, and I want to know how best to select user parameters from a URL.
I have some controllers that have index , add , edit and delete methods. The index action can take the page parameter, and the edit and delete actions can take the id parameter.
Examples http://example.com/somecontroller/index/page/1 http://example.com/someController/edit/id/1 http://example.com/otherController/delete/id/1
So far, I have used these parameters in action methods like this:
class somecontroller extends Zend_Controller_Action { public function indexAction() { $page = $this->getRequest->getParam('page'); } }
However, a colleague told me about a more elegant solution using Zend_Controller_Router_Rewrite as follows:
$router = Zend_Controller_Front::getInstance()->getRouter(); $route = new Zend_Controller_Router_Route( 'somecontroller/index/:page', array( 'controller' => 'somecontroller', 'action' => 'index' ), array( 'page' => '\d+' ) ); $router->addRoute($route);
This would mean that for each controller I would need to add at least three routes:
- one for the "index" action with parameter: page
- one for the change action with parameter: id
- one for the delete action with parameter: id
See the code below. These are routes for only 3 basic methods of action of one controller, imagine that you have 10 or more controllers ... I canβt imagine that this would be the best solution. The only thing I see is that the parameter keys are named and therefore can be omitted from the URL ( somecontroller/index/page/1 becomes somecontroller/index/1 )
// Route for somecontroller::indexAction() $route = new Zend_Controller_Router_Route( 'somecontroller/index/:page', array( 'controller' => 'somecontroller', 'action' => 'index' ), array( 'page' => '\d+' ) ); $router->addRoute($route); // Route for somecontroller::editAction() $route = new Zend_Controller_Router_Route( 'somecontroller/edit/:id', array( 'controller' => 'somecontroller', 'action' => 'edit' ), array( 'id' => '\d+' ) $router->addRoute($route); // Route for somecontroller::deleteAction() $route = new Zend_Controller_Router_Route( 'somecontroller/delete/:id', array( 'controller' => 'somecontroller', 'action' => 'delete' ), array( 'id' => '\d+' ) $router->addRoute($route);