路由定义内的条件

时间:2015-11-09 14:27:20

标签: php regex zend-framework routing zend-framework2

我刚开始使用ZendFramework 2。我在module.config.php中定义了一条路线,并希望在我的视图中使用$this->url来生成网址。

module.config.php

'settings-users-list' => array(
    'type'    => 'Zend\Mvc\Router\Http\Regex',
    'options' => array(
        'regex' => '/settings((/role/(?<role>[a-zA-Z]+))|)((/search/(?<search>[a-zA-Z0-9_-]+))|)((/page/(?<page>[0-9]+))|)((/date/(?<date>asc|desc))|)((/log/(?<log>asc|desc))|)',
        'defaults' => array(
            'controller' => 'Admin\Controller\Settings',
            'action' => 'index',
        ),
        'spec' => '/settings/role/%role%/search/%search%/page/%page%/date/%date%/log/%log%',
    ),
),

In my view

echo $this->url('admin/settings-users-list',$link_params,array('force_canonical' => true));

,其中

$link_params = array(
    'controller' => 'settings',
    'action'     => 'index',
    'role'       => 'admin',
    'search'     => '',
    'page'       => '', 
    'date'       => '', 
    'log'        => '', 
);

我的问题是,当我的一部分参数为空时,生成的网址不是所需的网址。在这种情况下,生成的URL是:

www.mysite.com/admin/settings/role/admin/search//page//date//log/

如果未设置此参数,是否有办法不显示searchpagedatelog。也许有办法在spec的{​​{1}}路线的settings-users-list字段中添加条件。

1 个答案:

答案 0 :(得分:2)

在您的情况下,我建议您不要将searchpagedatelog等搜索参数添加到您的路线中。这些是查询参数,对于这个ZF2,url帮助器在选项中有一个特殊的query键。您也可以在ZF2 url视图帮助文档的 enter image description here 段落中找到它。在您的情况下,您可以像这样使用它:

$params = array(
    'controller' => 'settings',
    'action'     => 'index',
    'role'       => 'admin'
);

$query = array(
    'search'     => '',
    'page'       => '', 
    'date'       => '', 
    'log'        => ''
);

$options = array(
   'force_canonical' => true,
   'query' => $query
);

echo $this->url('admin/settings-users-list', $params, $options);

我还建议简化你的路由器。没有正则表达式,它将更具可读性:

'settings' => array(
    'type'    => 'Literal',
    'options' => array(
        'route' => '/settings'
    )
    'may_terminate' => false,
    'child_routes' => array(
        'role' => array(
            'type'    => 'Segment',
            'options' => array(
                'route' => '/role/:role'
                'constraints' => array(
                    'role' => '[a-zA-Z]*'
                ),
                'defaults' => array(
                    'controller' => 'Application\Controller\Settings',
                    'action' => 'index',
                )
            )
        )
    )
),

然后你可以这样做:

echo $this->url('settings/role', $params, $options);