我正在尝试访问模型中的 getServiceLocator 函数。它在 Controller 中工作,但是当我将它移动到模型中时,我在尝试访问时得到 NULL。
Call to a member function get() on null
似乎下面的链接提供了类似的解决方案,但我在实现时遇到了麻烦
Use another module in our custom helper in zend framework 2
下面是我试图在模型中运行的代码。
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class FileManager implements ServiceLocatorAwareInterface {
someFunction(){
$thumbnailer = $this->getServiceLocator()->get('WebinoImageThumb');
}
}
谢谢 中号
最佳答案
如果可能的话,您不应该尝试在除工厂之外的任何类中访问 ServiceLocator。这样做的主要原因是,如果将 ServiceLocator 注入(inject)到您的类中,您现在不知道该类的依赖项是什么,因为它现在可能包含任何内容。
关于依赖注入(inject),您有两个基本选择:构造器注入(inject)或 setter 注入(inject)。根据经验,总是更喜欢构造函数注入(inject)。 Setter 注入(inject)应该只用于可选的依赖项,它还会使您的代码更加模糊,因为该类现在是可变的。如果您使用纯粹的构造函数注入(inject),您的依赖项是不可变的,并且您始终可以确定它们会存在。
使用 View 助手,您将使用 __invoke
而不是 __construct
来注入(inject)您的依赖项。
参见 https://stackoverflow.com/a/18866169/1312094有关如何设置类以实现 FactoryInterface
关于php - 如何访问 Model ZF2 中的 getServiceLocator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857188/