php - 如何访问 Model ZF2 中的 getServiceLocator

标签 php zend-framework zend-framework2

我正在尝试访问模型中的 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/

相关文章:

php - 配置 SAPRFC + PHP5 失败

php - NSDebugDescription = "JSON text did not start with array or object and option to allow fragments not set.";

php - ZF2 select 不显示任何结果

php - ZF2、Oracle、SlmQueueDoctrine、ClearObjectManagerStrategy 不工作

mysql - 学说 ZF2 : Can not able to save data for oneToMany Relation

javascript - 如何在页面加载时使用 JavaScript Alertify?

mysql - Zend DB 联盟不工作

php - 如何知道客户端的Magento配置

zend-framework - View 助手插件的多个实例?

提交表单后 PHP 得到空白页 + 信号段错误 (11)