As I delve deeper and deeper into Zf2 I find myself constantly Googling to find answers of best approaches to use when developing with Zf2. Unfortunately given the framework is still early on in its life many of these questions have yet to be asked (… or if they have been asked there sometimes aren’t answers).

One such question I was looking to solve was, how exactly do you create your own custom plugin manager in Zf2?

At first this seemed like a rather trivial task, inject the plugin manager configuration into the service manager using the module.config.php file. This seemed like too much overhead and has some unwanted limitations (eg. injecting plugins via something like getControllerPluginConfig in a Module.php file).

Looking at how the existing plugin managers are configured in Zend\Mvc\Service\ModuleManagerFactory it seemed like something that could be done easily enough to do in the onBootstrap function of the module containing the plugin manager. Unfortunately this didn’t work because onBootstrap is called too late in the initialization process for the plugin manager to be constructed correctly. Finally, I discovered the init function which is called early enough for the plugin manager to be constructed correctly, below is an example solution.

The below code ensures the plugin manager is correctly configured when requested from the service manager.

 * @param ModuleManager $moduleManager
public function init(ModuleManager $moduleManager)
    /** @var ServiceLocatorInterface $sm */
    $sm = $moduleManager->getEvent()->getParam('ServiceManager');
    /** @var ServiceListenerInterface $serviceListener */
    $serviceListener = $sm->get('ServiceListener');
        // The name of the plugin manager as it is configured in the service manager,
        // all config is injected into this instance of the plugin manager.
        // The key which is read from the merged module.config.php files, the
        // contents of this key are used as services for the plugin manager.
        // The interface which can be specified on a Module class for injecting 
        // services into the plugin manager, using this interface in a Module 
        // class is optional and depending on how your autoloader is configured
        // it may not work correctly.
        // The function specified by the above interface, the return value of this
        // function is merged with the config from 'sample_plugins_config_key'.

A full example module can also be downloaded from:

This module can be dropped into the ZendSkeletonApplication and accessed via “/sample-plugin-manager” in the browser.

Hopefully this information proves useful to someone else, it certainly would have saved me a little time. :)