如何访问 Model ZF2 中的 getServiceLocator [英] How do I access the getServiceLocator in Model ZF2

查看:23
本文介绍了如何访问 Model ZF2 中的 getServiceLocator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问模型中的 getServiceLocator 函数.它在控制器中工作,但是当我将它移动到模型中时,我在尝试访问时得到 NULL.

I am trying to access the getServiceLocator function in a model. It works in the controller but when I move it into a model I get NULL when trying to access.

 Call to a member function get() on null

似乎下面的链接提供了一个类似的解决方案,但我在实施时遇到了麻烦

It seemed like below link offered a comparable solution but I had trouble implementing

在我们的自定义助手中使用另一个模块在 Zend 框架 2 中

下面是我试图在模型中运行的代码.

Below is the code I am trying to run in a model.

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FileManager implements ServiceLocatorAwareInterface {

someFunction(){
    $thumbnailer = $this->getServiceLocator()->get('WebinoImageThumb');
    }
}  

谢谢米

推荐答案

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

When at all possible, you should not try to access the ServiceLocator inside any class except a factory. The main reason for this is that if the ServiceLocator is injected into your class, you now have no idea what that class's dependencies are, because it now could potentially contain anything.

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

With regard to dependency injection, you have two basic choices: constructor or setter injection. As a rule of thumb, always prefer constructor injection. Setter injection should only be used for optional dependencies, and it also makes your code more ambiguous, because the class is now mutable. If you use purely constructor injection, your dependencies are immutable, and you can always be certain they will be there.

使用视图助手,您将使用 __invoke 而不是 __construct 来注入您的依赖项.

With view helpers, you will use __invoke instead of __construct to inject your dependencies.

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

See https://stackoverflow.com/a/18866169/1312094 for a good description of how to set up a class to implement FactoryInterface

这篇关于如何访问 Model ZF2 中的 getServiceLocator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆