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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With