0

Okay so I'm using ZF2 with Doctrine's ORM Module

I have a model called ProjectGateway.php

My question is how do I access the service locator via getServiceLocator()-> I get call to undefined class error.

Does the model need to extend a class? Am I missing some imports?

I am able to access it via the controller.

Any steer in the right direction would be much appreciated.

4

1 回答 1

4

有两种方法可以做到这一点:

  1. 将模型作为服务添加到ServiceManager配置中,并确保模型类实现Zend\Service\ServiceLocatorAwareInterface该类。
  2. 通过 getter/setter 通过另一个使用 的类手动将服务管理器添加到模型中ServiceManager,例如。一个Controller

方法一:

// module.config.php
<?php
return array(
    'service_manager' => array(
        'invokables' => array(
            'ProjectGateway' => 'Application\Model\ProjectGateway',
        )
    )
);

现在确保您的模型实现了ServiceLocatorAwareInterface及其方法:

namespace Application\Model;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ProjectGateway implements ServiceLocatorAwareInterface 
{
    protected $serviceLocator;

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
        $this->serviceLocator = $serviceLocator;
    }

    public function getServiceLocator() {
        return $this->serviceLocator;
    }
}

现在,您可以通过以下方式从控制器中获取您的信息ProjectGateway

$projectGateway = $this->getServiceLocator->get('ProjectGateway');

因此,您现在可以ProjectGateway通过执行以下操作在您的类中使用 ServiceManager:

public function someMethodInProjectGateway()
{
    $serviceManager = $this->getServiceLocator();
}

2014 年 4 月 6 日更新:方法 2:

基本上,您在模型中需要的是ServiceManager方法 1 中所示的 getter/setter,如下所示:

namespace Application\Model;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ProjectGateway implements ServiceLocatorAwareInterface 
{
    protected $serviceLocator;

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
        $this->serviceLocator = $serviceLocator;
    }

    public function getServiceLocator() {
        return $this->serviceLocator;
    }
}

然后你需要从其他地方(例如 a )做的就是在那里Controller解析:ServiceManager

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Application\Model\ProjectGateway;

class SomeController extends AbstractActionController
{
    public function someAction()
    {
        $model = new ProjectGateway();

        // Now set the ServiceLocator in our model
        $model->setServiceLocator($this->getServiceLocator());
     }
}

仅此而已。

然而,使用方法 2 意味着该ProjectGateway模型在您的应用程序中无法随需应变。您需要ServiceManager每次都实例化和设置。

但是,作为最后一点,必须注意方法 1 的资源并不比方法 2 重,因为模型在您第一次调用它之前没有实例化。

于 2013-09-23T14:43:22.893 回答