ZF2 getServiceLocator() not found?

2019-04-10 02:29发布

问题:

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 

回答1:

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 ;)



回答2:

I think it is besause your Controller isn't implement the interface of ServiceLocatorAwareInterface.You can see the class Zend\ServiceManager\AbstractPluginManager,in the construct 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);
        }
    });
}

so you must implement it if you want use the ServiceLocator,or extend the class Zend\Mvc\Controller\AbstractActionController it have implementd the ServiceLocatorAwareInterface.