Jimit
Jimit

Reputation: 2259

How do I get service manager object in module.php file in zendframework 2?

I found below function in module.php file of ZendFramework 2 module. I don't understand how do I get object of service manager($sm) in this function?

`

public function getControllerConfig()  
    {
        return array(  
             'initializers' => array(    
                function($instance, $sm){      
                      if($instance instanceof Service\FormServiceAwareInterface){  
                        $sm = $sm->getServiceLocator();
                        $formService = $sm->get('some_service');
                        $instance->setFormService($formService);
                      }
                 },
              ),
          );
      }

`

Can anyone explain how do I get object $sm in getControllerConfig function?

Upvotes: 0

Views: 1802

Answers (1)

AlloVince
AlloVince

Reputation: 1655

When ZF2 start mvc process, all default services will be registered first.

Check manual you will know more about these services : http://framework.zend.com/manual/2.0/en/modules/zend.mvc.services.html

One of the most important services is ModuleManager which handle all modules related functions.

You could found ModuleManager start process in Zend\Mvc\Service\ModuleManagerFactory->createService().

Notice these codes:

$serviceListener->addServiceManager(
    'ControllerLoader',
    'controllers',
    'Zend\ModuleManager\Feature\ControllerProviderInterface',
    'getControllerConfig'
);

This will call Zend\ModuleManager\Listener\ServiceListener->addServiceManager() and save module name & method name for temporary.

Then when loadModule event triggered, Zend\ModuleManager\Listener\ServiceListener->onLoadModule() will be called. In this method, all returned results from Modele->getControllerConfig() will be register as service and put into Zend\ServiceManager\ServiceManager.

Finally, when you call services from getControllerConfig(), Zend\ServiceManager\ServiceManager->create() will be called, instance and ServiceManager will be set into your Closure as parameters by:

foreach ($this->initializers as $initializer) {
    if ($initializer instanceof InitializerInterface) {
        $initializer->initialize($instance, $this);
    } elseif (is_object($initializer) && is_callable($initializer)) {
        $initializer($instance, $this);
    } else {
        call_user_func($initializer, $instance, $this);
    }
}

I wrote a note about ZF2 Mvc process before when ZF2 under beta3, maybe could help you (could use google translate).

Upvotes: 1

Related Questions