rafaame
rafaame

Reputation: 822

Getting the service locator anywhere in ZF2

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?

Upvotes: 8

Views: 9641

Answers (2)

Mr Coder
Mr Coder

Reputation: 8186

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.

Upvotes: 6

IJMorgado
IJMorgado

Reputation: 137

Here is a simple way to get ServiceLocator to instantiate objects wherever you want...is a very simple module that set ServiceLocator on application's bootstrap to a static variable in a class...you can get an idea to create something more sophisticated if it doesn't fit your needs :) Here is the module... https://github.com/fezfez/ServiceLocatorFactory

Upvotes: 2

Related Questions