zf2 ServiceManager vs ServiceLocator
Asked Answered
K

2

15

I am learning zf2, reading docs, tutorials etc from the web. Now I am confused regarding Zend\ServiceManager\ServiceManagerAwareInterface.php and Zend\ServiceManager\ServiceLocatorAwareInterface.php.

Also in some place (like controller) I use $this->getServiceLocator() to fetch the ServiceManager object while at some other places we use ->getServiceManager() and it also returns the same ServiceManager object.

Koniology answered 8/9, 2013 at 10:50 Comment(2)
@Sam, Why do we need both methods then?Dutra
But why are there two interfaces. Zend\ServiceManager\ServiceManagerAwareInterface.php and Zend\ServiceManager\ServiceLocatorAwareInterface.php. If SM is the implementaion of SL, why do we have a separate interface.Koniology
H
16

The Locator is the interface. The design of Zend Framework 2 is done with "design by contract" which means you rely on interfaces rather than classes. The Manager is a default implementation of the Locator.

All but one component use the Locator. However, the manager provides more features than the interface says. The Zend\Mvc\Application uses these features and therefore relies on the Manager instead of the Locator.

The decision to use the Locator in the *Aware initializers was made too late for the release, so this is why there is both a ServiceLocatorAwareInterface and a ServiceManagerAwareInterface. There was already userland code using the Manager's initializer so it's kept for backwards compatibility. Internally all components use the Locator initialzer. If you have to choose, pick the Locator and leave the Manager as much as possible aside.

Quite some time ago I also blogged about the Locator and the Manager: https://juriansluiman.nl/article/120/using-zend-framework-service-managers-in-your-application

Hermetic answered 8/9, 2013 at 19:35 Comment(0)
A
5

The ServiceManager is basically the implementation of the ServiceLocator interface. The reason of having the two is that a user can have their own implementation of the ServiceLocator interface. When you request the ->getServiceManager() it returns you the explicit ServiceManager implementation. By using ->getServiceLocator() you are requesting any implementation of the ServiceLocator interface which can be the implementation by the ServiceManager or your own. But as most of the times there is only the default ServiceManager implelmentation so you will get the same object.

Anethole answered 8/9, 2013 at 11:0 Comment(2)
that makes some sense but again why do we have Zend\ServiceManager\ServiceManagerAwareInterface.php. and which approach do you think should be used.Koniology
i stick with the ServiceLocator as it also has a trait available, so I just use the trait and don't have to implement the SL/SM on my own over and over.Anethole

© 2022 - 2024 — McMap. All rights reserved.