繁体   English   中英

找不到ZF2 getServiceLocator()?

[英]ZF2 getServiceLocator() not found?

我不能为我的生活让$ 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');
    }
    ...

我得到的错误是:

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)仅在Controller的生命周期的稍后时间点可用。 如果您希望分配一个可以在整个动作中轻松使用的变量,我建议使用Lazy-Getters或使用工厂模式注入它们

懒惰干将

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

希望这是可以理解的;)

我认为这是因为你的Controller没有实现ServiceLocatorAwareInterface的接口。你可以在构造方法中看到类Zend \\ ServiceManager \\ AbstractPluginManager:

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

所以你必须实现它,如果你想使用ServiceLocator,或者扩展类Zend \\ Mvc \\ Controller \\ AbstractActionController它已经实现了ServiceLocatorAwareInterface。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM