找不到ZF2 getServiceLocator()?

Dan*_*eph 4 php zend-framework2

我不能为我的生活让$ this-> getServiceLocator()在我的控制器中工作.我已经阅读并尝试了一切.我猜我错过了什么?这是一些代码.

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');
    }
    ...
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

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 
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 5

让我的评论更具意义.ServiceLocator(或者更确切地说,所有ControllerPlugins)仅在Controller的生命周期的稍后时间点可用.如果您希望分配一个可以在整个动作中轻松使用的变量,我建议使用Lazy-Getters或使用工厂模式注入它们

懒惰干将

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

工厂模式

//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;
}
Run Code Online (Sandbox Code Playgroud)

希望这是可以理解的;)