Getting a service locator anywhere in ZF2

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

ServiceManager is a "short simple application registry that provides objects." Therefore, I would think that this should be one single that we can get anywhere in the application. But in the case of ServiceManager, this is not so.

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

+6
source share
2 answers

ServiceManager basically acts as a container. Inside the container, you satisfy the various dependencies of the created object and then return it for use by other objects.

So, somehow SM sits above the object, and does not enter the object. If you use an SM instance inside an object (possibly to access other services), you go against the principle of inverse control.

Below are two ways:

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

Another 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 the second example, the dependency ( $user_data ) is injected into the object.

+5
source

Here is a simple way to get ServiceLocator to create objects where you want ... is a very simple module that sets ServiceLocator to load the application on a static variable in the class ... you can get an idea of ​​creating something more complex if it isn’t fits your needs :) Here is the module ... https://github.com/fezfez/ServiceLocatorFactory

+1
source

Source: https://habr.com/ru/post/946320/


All Articles