Overriding module configuration in ZF2

Let's say that you install the ZF-Common's User module. By default, it sets up its routes under the /user path segment like this:

vendor/ZfcUser/config/module.config.php

<?php
return array(
// lots of config stuff here

            /**
             * Routes
             */

            'ZendMvcRouterRouteStack' => array(
                'parameters' => array(
                    'routes' => array(
                        'zfcuser' => array(
                            'type' => 'Literal',
                            'priority' => 1000,
                            'options' => array(
                                'route' => '/user',
                                'defaults' => array(
                                    'controller' => 'zfcuser',
                                    'action'     => 'index',
                                ),
                            ),
                            'may_terminate' => true,
                            'child_routes' => array(
                                'login' => array(
                                    'type' => 'Literal',
                                    'options' => array(
                                        'route' => '/login',
                                        'defaults' => array(
                                            'controller' => 'zfcuser',
                                            'action'     => 'login',
                                        ),
                                    ),
                                ),

// more config stuff here
);

This config section will create the routes /user and through the magic of child_routes, also create /user/login and other required routes.

If you don't want /user and would prefer /member, then it's easy enough to change. Just add a new config file to the project's config/autoload folder:

config/autoload/module.zfcuser.override.config.php

<?php

return array(
    'di' => array(
        'instance' => array(

           'Zend\Mvc\Router\RouteStack' => array(
                'parameters' => array(
                    'routes' => array(
                        'zfcuser' => array(
                            'options' => array(
                                'route' => '/member',
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),    
);

As a result of using child_routes, all the other routes under this route will pick up the same segment, so /user/login is now accessed via /member/login. Also, as each route is named independently from its route, all the url view helper calls continue to work as the route's name continues to be zfcuser/login.

Obviously, this technique works for any other config setting that you may wish to override.

If you would like to comment on this article, please ping me on twitter.
If your response won't fit into 140 characters, write a blog post and then ping me!