Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use URL segments as action method parameters in Zend Framework

In Kohana/CodeIgniter, I can have a URL in this form:

http://www.name.tld/controller_name/method_name/parameter_1/parameter_2/parameter_3 ...

And then read the parameters in my controller as follows:

class MyController 
{
    public function method_name($param_A, $param_B, $param_C ...)
    {
        // ... code
    }
}

How do you achieve this in the Zend Framework?

like image 623
Jeffrey04 Avatar asked Oct 02 '08 09:10

Jeffrey04


2 Answers

Take a look at the Zend_Controller_Router classes:

http://framework.zend.com/manual/en/zend.controller.router.html

These will allow you to define a Zend_Controller_Router_Route which maps to your URL in the way that you need.

An example of having 4 static params for the Index action of the Index controller is:

$router = new Zend_Controller_Router_Rewrite();

$router->addRoute(
    'index',
    new Zend_Controller_Router_Route('index/index/:param1/:param2/:param3/:param4', array('controller' => 'index', 'action' => 'index'))
);

$frontController->setRouter($router);

This is added to your bootstrap after you've defined your front controller.

Once in your action, you can then use:

$this->_request->getParam('param1');

Inside your action method to access the values.

Andrew

like image 73
Andrew Taylor Avatar answered Sep 20 '22 18:09

Andrew Taylor


Update (04/13/2016): The link in my answer below moved and has been fixed. However, just in case it disappears again -- here are a few alternatives that provide some in depth information on this technique, as well as use the original article as reference material:

  • Zend Framework Controller Actions with Function Parameters
  • Zend_Controller actions that accept parameters?

@Andrew Taylor's response is the proper Zend Framework way of handling URL parameters. However, if you would like to have the URL parameters in your controller's action (as in your example) - check out this tutorial on Zend DevZone.

like image 42
leek Avatar answered Sep 17 '22 18:09

leek