开发者

Zend_Controller_Router_Route_Regex allow '?' in pattern

开发者 https://www.devze.com 2023-02-10 15:15 出处:网络
Imagine situation, when the url should looks like /catalog/sectionIdent?page=1 where page param is optional.

Imagine situation, when the url should looks like

/catalog/sectionIdent?page=1

where page param is optional.

Of course, custom route should be defined. Consider the following code:

    $route = new Zend_Controller_Router_Route_Regex(
        'catalog/([-a-z]+)(?:\?page=([0-9]*))?',
        array('controller'=>'catalog','action'=>'list','page'=>''),
        array(1=>'section',2=>'page'),
        'catalog/%s?page=%d'
    );
    $router->addRoute('catalog-section-page',$route); 

But this route won't be triggered with '?' symbol in url.

Without '?' (for example, by adding escaped '!' symbol to pattern) everything works as it should. Is there any way to achieve '?' presence in custom defined regex route? Maybe I'm doing something wrong in pa开发者_开发问答ttern?

P.S.: Don't offer to use '/' instead of '?', question is exactly about pattern restrictions in Zend_Controller_Router_Route_Regex implementation.


The ZF routing classes operate on the REQUEST_URI with the query string stripped off, so you may have a hard time get this working in the way you are expecting. However, I believe GET parameters are put into the request object by default, so you shouldn't need to cater for them in your routes. I'd suggest changing your route to remove the query string parts:

$route = new Zend_Controller_Router_Route_Regex(
    'catalog/([-a-z]+)',
    array('controller'=>'catalog','action'=>'list'),
    array(1=>'section'),
    'catalog/%s'
);
$router->addRoute('catalog-section-page',$route); 

You should still be able to access the params in your controller as if they had been populated by the routes:

public function listAction()
{
    echo $this->_getParam('page');
}

and you can use the same method to set a default:

public function listAction()
{
    $page = $this->_getParam('page', 1); // defaults to 1 if no page in URL
}

You just may need to sanitise them there (make sure they are numeric).

Edit:

Example of URL helper with this route:

echo $this->url(array('section' => 'foo', 'page' => 2), 'catalog-section-page') 
0

精彩评论

暂无评论...
验证码 换一张
取 消