How do I access the getServiceLocator in Model ZF2

烂漫一生 提交于 2019-12-10 19:35:12

问题


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

Use another module in our custom helper in zend framework 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');
    }
}  

Thank you M


回答1:


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.

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.

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

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



来源:https://stackoverflow.com/questions/32857188/how-do-i-access-the-getservicelocator-in-model-zf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!