Search code examples
zend-framework2

How to select controller namespace with Zend Framework 2 routing?


I have this as part of my DI config, from the skeleton applicaiton:

                'routes' => array(
                    'default' => array(
                        'type'    => 'Zend\Mvc\Router\Http\Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                                'controller' => 'Application\Controller\IndexController',
                                'action'     => 'index',
                            ),
                        ),
                    ),  

I would like to make the following routings:

http://me.com/mycontroller/myaction --> 
controller=Applicaiton\Controller\Mycontroller 
method=myactionAction

However, the above config produces:

http://me.com/mycontroller/myaction --> 
controller=Mycontroller 
method=myactionAction

As you can see, the namespace for the controller is missing. Where/how do I put the namespace in? (I know I could make a DI alias for every controller, but that would deafeat the purpose of having segment matching.)


Solution

  • You should not use segments for controllers in your routes. Segment matching is possible for actions and other parameters, but not for controllers. You might use aliases to help mycontroller match MyNamespace\Mycontroller, but it is not recommended. The best, easiest and with the most performance way is to have routes for every controller, use segments for actions if necessary.