phpzend-framework2zend-framework-modules

How to create a generic module/controller/action route in Zend Framework 2?


I would like to create a generic module/controller/action route in Zend Framework 2 to be used with ZF2 MVC architecture.

In ZF1 the default route was defined like /[:module][/:controller][/:action] where module would default to default, controller would default to index and action to index.

Now, ZF2 changed the way modules are intended, from simple groups of controllers and views, to real standalone applications, with explicit mapping of controller name to controller class.

Since all controller names must be unique across all modules, I was thinking to name them like modulename-controllername but I would like the URL to look like /modulename/controllername without the need to create specific routes for each module, using something like the old default route for ZF1 described above.


Solution

  • Yes it is very possible, but you will have to do a little work. Use the following config:

            'default' => array(
                'type'    => 'My\Route\Matcher',
                'options' => array(
                    'route'    => '/[:module][/:controller[/:action]]',
                    'constraints' => array(
                        'module' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'module'     => 'default',
                        'controller' => 'index',
                        'action'     => 'index',
                    ),
                ),
            ),
    

    Then you have to write your own My\Route\Matcher to create a Routemap object that the MVC can use. It's not hard, look at the other route matchers already in the framework and you'll get the idea.