Router_Route with optional parameters

2019-04-06 15:07发布

问题:

I have the following route:

        $gridRoute = new Zend_Controller_Router_Route(
        ':module/:controller/list/:order/:dir/:page',
        array (
            'module' => 'default',
            'controller' => 'index',
            'order' => '',
            'dir' => 'asc',
            'page' => 1,
            'action' => 'list'
        ),
        array (
            'page' => '\d+'
        )
    );
    $router->addRoute('grid', $mainRoute->chain($gridRoute));

I would like to be able to add an optional parameter 'filter' to this route. So I could use the following url:

http://example.org/default/list/filter/all/lname/asc/1 or http://example.org/default/list/lname/asc/ or http://example.org/default/list/filter/all

Either one should work. I tried to place an optional parameter in the Route but that did not work. Any ideas?

回答1:

Typically, in Zend's Router, like in PHP, an optional parameter is a parameter that has a default value. Add one for the filter parameter:

$gridRoute = new Zend_Controller_Router_Route(
    ':module/:controller/list/:order/:dir/:page/:filter',
    array (
        'module' => 'default',
        'controller' => 'index',
        'order' => '',
        'dir' => 'asc',
        'page' => 1,
        'action' => 'list',
        'filter' => null, // define default for filter here
    ),
    array (
        'page' => '\d+'
    )
);