本文介绍了找不到 ZF2 getServiceLocator()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一辈子都无法让 $this->getServiceLocator() 在我的控制器中工作.我已经阅读并尝试了一切.我猜我错过了什么??这是一些代码.

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');
    }
    ...

我得到的错误是:

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 

推荐答案

让我的评论更有意义.ServiceLocator(或所有 ControllerPlugins)仅在控制器生命周期的后期可用.如果您希望分配一个可以在整个操作中轻松使用的变量,我建议您使用 Lazy-Getters 或使用 Factory 模式

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

懒惰的人

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

工厂模式

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

这篇关于找不到 ZF2 getServiceLocator()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:58