Getting the service locator anywhere in ZF2

rafaame picture rafaame · Jun 1, 2013 · Viewed 9.6k times · Source

According to this article: http://www.maltblue.com/tutorial/zend-framework-2-servicemanager

The ServiceManager is "in short a simple application registry that provides objects". So, I would think that it should be a singleton that we can have access anywhere in the application. But in case of ServiceManager, it isn't.

Why can't I get the service locator instance anywhere in the application?

Answer

Mr Coder picture Mr Coder · Jun 2, 2013

ServiceManager basically act as container. Inside the container you satisfy various dependencies of an object you create and then return it to be used by other objects.

So in a way SM sits over the object, not goes inside the object. If you are using SM instance inside the object (probably to access other services) then you are going against the principle of Inversion of Control.

Following are the two ways

class A {    
    private $data;
    public function __constructor($sm) {
        $this->data = $sm->get('user_data'); // Service manager accessed inside the object
    }
}

Other way

class B {
    private $data; 
    public function __constructor($user_data) {
            $this->data = $user_data;     //$user_data getting injected from sm container 
    }
}

Somewhere inside Module.php:

'factories'=>        
    array(
        'objB'=> function($sm) {
            //this is the container where sm sites outside the object to satisfy its dependencies
            $objB = new B($sm->get('user_data'));  
            return $objB;
        }
    )

In second example dependency ($user_data) gets injected into the object.