Multiple config files for ZF2 module

Consider a ZF2 module which contains configuration for view templates, controllers, service managers, routes, navigation etc. by default module configs are stored in module/config/module.config.php, if a module has fewer functionality, storing module config in one single file works fine and makes sense, however it becomes hard to manage when more configurations are added, hence, I personally prefer to store configurations in different config files, this way it becomes way easier to manage.

Depending on type of configuration you are using in zf2-module, it can be organized in separate config files, for example

module.config.php to store general module config
routes.config.php to store routes config
navigation.config.php to store navigation config and so on…

Create your desired config files in module/config directory, once the config files are created, we need to inform ZF2 to load the config files, to do this open your module/Module.php file and update Module::getConfig() and update to following

public function getConfig()
{
    return array_merge_recursive(
        include __DIR__ . '/config/module.config.php',
        include __DIR__ . '/config/navigation.config.php',
        include __DIR__ . '/config/route.config.php'
    );
}

As you have noticed, we make use of array_merge_recursive to merge config files and return merged array in getConfig(), make sure to return an array in all of your config files and it’ll work.

Leave A Comment

Your email address will not be published. Required fields are marked *