zend-frameworkdependency-injectionzend-framework2zend-framework-mvc

How configure Zend\Di


I need a help with Zend\Di;

I'm tired on the task of write factories to my application using the Zend\ServiceManager, I want to understand how work the configuration in MVC environment of Zend\Di.

I see this post of @Ocramius, with some configuration in the module.config.php, in the top key di:

<?php

return array(
    'di' => array(
        'allowed_controllers' => array(
            // this config is required, otherwise the MVC won't even attempt to ask Di for the controller!
            'Application\Controller\GreetingController',
        ),

        'instance' => array(
            'preference' => array(
                // these allow injecting correct EventManager and ServiceManager
                // (taken from the main ServiceManager) into the controller,
                // because Di doesn't know how to retrieve abstract types. These
                // dependencies are inherited from Zend\Mvc\Controller\AbstractController
                'Zend\EventManager\EventManagerInterface' => 'EventManager',
                'Zend\ServiceManager\ServiceLocatorInterface' => 'ServiceManager',
            ),
        ),
    ),
    // remaining config
);

Anyone can post a url to the doc of this configuration or more detailed examples here?


Solution

  • If you have a lot of different controllers and have a lot of services to choose from, then the ones with Configuration or Annotation should be the choices in this link: https://github.com/ralphschindler/Zend_DI-Examples

    I think you should look at some libraries like Aura.Di or Pimple. They provide even powerful DI containers.

    If you have minimal services to inject, use initializers. Check this out: http://akrabat.com/zend-framework-2/zendservicemanager-configuration-keys/