如何访问Model ZF2中的getServiceLocator

时间:2015-09-30 03:19:08

标签: php zend-framework zend-framework2

我正在尝试访问模型中的getServiceLocator函数。它在控制器中工作但是当我将它移动到模型中时,我在尝试访问时得到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');
    }
}  

谢谢 中号

1 个答案:

答案 0 :(得分:8)

如果可能的话,您不应该尝试访问除工厂之外的任何类中的ServiceLocator。这样做的主要原因是如果将ServiceLocator注入到您的类中,您现在不知道该类的依赖项是什么,因为它现在可能包含任何内容。

关于依赖注入,您有两个基本选择:构造函数或setter注入。根据经验,总是更喜欢构造函数注入。 Setter注入只应用于可选的依赖项,并且它还会使您的代码更加模糊,因为该类现在是可变的。如果你使用纯粹的构造函数注入,你的依赖项是不可变的,你总是可以确定它们会在那里。

使用视图助手,您将使用__invoke代替__construct来注入您的依赖项。

有关如何设置类以实现FactoryInterface的详细说明,请参阅https://stackoverflow.com/a/18866169/1312094

相关问题