如何在Zend Framework 2中使用路由传递参数? [英] how to pass params using a route in Zend Framework 2?

查看:86
本文介绍了如何在Zend Framework 2中使用路由传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个路由器test/view,我想传递一些参数,例如test/view/id/123.

i have a router test/view and i would like to pass some params like test/view/id/123.

我不确定如何在zf2路由器中添加这些参数.

Im not sure how to add those params in the zf2 router.

'router' => array(
        'routes' => array(
            'test' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/test',
                    'defaults' => array(
                        '__NAMESPACE__' => 'test\Controller',
                        'controller'    => 'Index',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'view' => array(
                        'type' => 'Literal',
                        'options' => array(
                            'route' => '/view',
                            'defaults' => array(
                                'controller' => 'Index',
                                'action'     => 'view',
                            ),
                        ),
                    ),
                ),
            ),
        ),
),

我将view设置为子路径,但不确定在何处添加这些参数.

i setup view as a child route but not sure where to add those params.

我尝试了'route' => '/view/:id/:value'

'defaults' => array(
    'controller' => 'Index',
    'action'     => 'view',
    'id'         => 'value',
)

但它们似乎不起作用

我正试图了解所有这些工作原理.

i am trying to understand how all this works.

有什么想法吗?谢谢

推荐答案

'router' => array(
    'routes' => array(
        'test-view' => array(
            'type'    => 'segment',
            'options' => array(
                'route'    => '/test/view/:testId[/]',
                'constraints' => array(
                    'testId'     => '[0-9]+',
                ),
                'defaults' => array(
                    'controller' => 'Test\Controller\Index',
                    'action' => 'view'
                ),
            ),
        ),

然后在ControllerAction中,您可以使用以下方法获取参数"testId":

In your ControllerAction you can then get the parameter "testId" by using:

$this->params('testId');

顺便说一句:上面的路线为您提供了这样的网址:/test/view/123-我认为您可能会摆脱"id"参数.

Btw: The above route gives you an url like this: /test/view/123 - I thought you may get rid of the "id" param.

如果要创建到此类页面的链接,则可以在其中一个视图中使用$this->url('test-view', array('testId' => 123)).

If you want to create a link to one kind of this pages, you can use $this->url('test-view', array('testId' => 123)) in one of your views.

这篇关于如何在Zend Framework 2中使用路由传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆