0

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

路线一:

            '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。但它不起作用。

4

1 回答 1

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 对整数的约束。

参考

于 2017-11-18T15:11:39.877 回答