Search code examples
phprouteszend-framework3

Zend Framework 3 - route based on query string


In Zend Framework 3, is it possible to route to a controller depending on whether a URL contains a query string?

For example, I have these two URLs:

/users
/users?name=Bob

I would like the first route to call a UsersController and second route to call a NameController.

Is this possible?


Solution

  • As rkeet mentioned, query string is not part of the route. Therefore, we simply added a ternary to the route config array:

    'users' => [ 
        'type'    => Literal::class,
        'options' => [ 
            'route'    => '/users',
            'defaults' => [
                'controller' => isset($_GET['name'])
                              ? NameController::class
                              : UsersController::class,
                'action'     => 'index',
            ],   
        ],   
        'may_terminate' => true,
    ],
    

    It's self explanatory, but basically the controller that is dispatched is dependent on whether a value is set in the query string.

    We decided not to use the forward() plugin because we do not want to instantiate an extra controller superfluously.