Zend Framework - routing same routes to different controller

104 Views Asked by At

I have two routes and want to match both routes when some parameter exists in request.

Route 1:

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

Route 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,
        ],

I want to use CompanyMembersController when members exists in the request and CompaniesController when members doesnt exists .But it is not working.

1

There are 1 best solutions below

0
Jannes Botis On

Your issue is in the second route where you defined members as a parameter [/:members]. You should change this to a /members.

I also would recommend to use constraints for your route parameters. Your routes should look like:

'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,
],

Also you can see the constraints to parameters id & member_id to integers.

References