zf2 ServiceManager 与 ServiceLocator [英] zf2 ServiceManager vs ServiceLocator
问题描述
我正在学习 zf2,从网上阅读文档、教程等.现在我对 Zend\ServiceManager\ServiceManagerAwareInterface.php
和 Zend\ServiceManager\ServiceLocatorAwareInterface.php
感到困惑.
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
.
也在某些地方(如控制器)我使用 $this->getServiceLocator()
来获取 ServiceManager
对象,而在其他一些地方我们使用 ->getServiceManager()
并且它也返回相同的 ServiceManager
对象.
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.
推荐答案
定位器是接口.Zend Framework 2 的设计是通过契约式设计"完成的,这意味着您依赖于接口而不是类.Manager 是 Locator 的默认实现.
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.
除一个组件外,所有组件都使用定位器.但是,管理器提供的功能比界面说的要多.Zend\Mvc\Application
使用这些功能,因此依赖于管理器而不是定位器.
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.
决定在 *Aware 初始值设定项中使用 Locator 对于发布来说为时已晚,所以这就是为什么同时存在 ServiceLocatorAwareInterface
和 ServiceManagerAwareInterface
的原因.已经有使用 Manager 的初始化程序的用户空间代码,因此保留它是为了向后兼容.在内部,所有组件都使用 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.
不久前我还写了关于定位器和管理器的博客:https://juriansluiman.nl/article/120/using-zend-framework-service-managers-in-your-application
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
这篇关于zf2 ServiceManager 与 ServiceLocator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!