ZF2 getServiceLocator() not found?

php, zend-framework2

Solution

To give my comment a little bit more meaning. The ServiceLocator (or rather all ControllerPlugins) are only available at a later point of the livecycle of the Controller. If you wish you assign a variable that you can easily use throughout your actions, i suggest to either use Lazy-Getters or to inject them using the Factory Pattern

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 that's understandable ;)

Problem

I can't for the life of me get $this->getServiceLocator() to work in my controller. I've read and tried everything. I'm guessing I'm missing something?? Here is some 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'm 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 ```

Original source

Related problems