Zend Framework - 将相同的路由路由到不同的控制器

时间:2017-11-18 10:07:13

标签: zend-framework2 zend-framework3 zend-framework-routing

我有两条路线,想要在请求中存在某些参数时匹配这两条路线。

路线1:

            'companies' => [
            'type' => Segment::class,
            'options' => [
                'route' => '/api/v1/companies[/:id]',
                'defaults' => [
                    'controller' => V1\Rest\Controller\CompaniesController::class,
                ]
            ],
            'priority' => 2,
            'may_terminate' => true,
        ],

路线2:

            'company_members' => [
            'type' => Segment::class,
            'options' => [
                'route' => '/api/v1/companies[/:id][/:members][/:member_id]',
                'defaults' => [
                    'controller' => V1\Rest\Controller\CompanyMembersController::class,
                ]
            ],
            'priority' => 2,
            'may_terminate' => true,
        ],

当成员存在于请求中时,我想使用CompanyMembersController,当成员不存在时,我想使用CompaniesController。但是它不起作用。

1 个答案:

答案 0 :(得分:0)

您的问题出在第二条路线中,您将成员定义为参数 [/:members] 。您应该将其更改为 / members

我还建议您对路线参数使用约束。您的路线应如下所示:

'companies' => [
    'type' => Segment::class,
    'options' => [
        'route' => '/api/v1/companies[/:id]',
        'defaults' => [
            'controller' => Controller\CompaniesController::class,
            'action'     => 'index',
        ],
        'constraints' => [
            'id' => '\d+'
        ]
    ],
    'priority' => 2,
    'may_terminate' => true,
],
'company_members' => [
    'type' => Segment::class,
    'options' => [
        'route' => '/api/v1/companies[/:id]/members[/:member_id]',
        'defaults' => [
            'controller' => Controller\CompanyMembersController::class,
            'action'     => 'index',
        ],
        'constraints' => [
            'id' => '\d+',
            'member_id' => '\d+',
        ]
    ],
    'priority' => 2,
    'may_terminate' => true,
],

您还可以看到约束参数id& member_id到整数。