Search code examples
phpzend-framework2

ZF2 - Controller managing route with and without params


I am writting an application with zf2 and I came to this issue which I don't know how to implement.

At the moment I have a router like this :

'routes' => [
        'stock' => [
            'type'    => 'regex',
            'options' => [
                'regex' => '/stock(?<sku>\/.*)',
                'defaults' => [
                    'controller' => MyController::class,
                    'action' => 'check',
                ],
                'spec' => '/path%path%'
            ],

So when my url contains ../stock/13567/2312 the parameter gets passed into the checkAction function.

However, I would like to show a different content when the url is just ../stock/ or ../stock without any parameter sent. How can I achieve this ?

Thanks.


Solution

  • Just augment the regex to mark the param as optional, as in the docs:

    'regex' => '/stock(?<sku>\/.*)?'
    

    ... and don't forget to provide the explicit default value:

    'defaults' => [
      'controller' => MyController::class,
      'action' => 'check',
      'sku'    => '' // or else
    ],