ZF2 getServiceLocator () not found?

I cannot get $ this-> getServiceLocator () for life in my controller for life. I read and tried everything. I guess I missed something? Here is the code.

namespace Login\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\Session\Container as SessionContainer; use Zend\Session\SessionManager; use Zend\View\Model\ViewModel; use Zend\Mvc\Controller; use Login\Model\UserInfo; class LoginController extends AbstractActionController { private $db; public function __construct() { $sm = $this->getServiceLocator(); $this->db = $sm->get('db'); } ... 

The error I am getting is:

 Fatal error: Call to a member function get() on a non-object in /product/WishList/module/Login/src/Login/Controller/LoginController.php on line 21 
+4
source share
2 answers

To give my comment a little more sense. ServiceLocator (or rather, all ControllerPlugins) are only available at a later point in the controller life cycle. If you want to assign a variable that you can easily use in all your actions, I suggest either using Lazy-Getters or entering them using the Factory Template

Lazy Getters

 class MyController extends AbstractActionController { protected $db; public function getDb() { if (!$this->db) { $this->db = $this->getServiceLocator()->get('db'); } return $this->db; } } 

Factory -Pattern

 //Module#getControllerConfig() return array( 'factories' => array( 'MyController' => function($controllerManager) { $serviceManager = $controllerManager->getServiceLocator(); return new MyController($serviceManager->get('db')); } )); //class MyController public function __construct(DbInterface $db) { $this->db = $db; } 

Hope this is clear;)

+5
source

I think this is because your controller does not implement the ServiceLocatorAwareInterface interface. You can see the Zend \ ServiceManager \ AbstractPluginManager class in the build method:

 public function __construct(ConfigInterface $configuration = null) { parent::__construct($configuration); $self = $this; $this->addInitializer(function ($instance) use ($self) { if ($instance instanceof ServiceLocatorAwareInterface) { $instance->setServiceLocator($self); } }); } 

therefore, you must implement it if you want to use the ServiceLocator, or extend the Zend \ Mvc \ Controller \ AbstractActionController class that it implemented in ServiceLocatorAwareInterface.

0
source

Source: https://habr.com/ru/post/1497068/


All Articles