2013-03-11 32 views
2

我一直在开发一个项目中的Zend 1,但决定移动到Zend的2拿东西就像优势等事件我如何从我自己的图书馆中的Zend 2进入getServiceLocator

我最初的问题是,我似乎无法找到任何关于如何以我需要使用它们的方式使用模型的教程。

什么我是被路由到AS/API/SOAP的API控制器

这种肥皂端点加载具有所有我想通过SOAP暴露

namespace MyProject\Controller; 

$view = new ViewModel(); 
$view->setTerminal(true); 
$view->setTemplate('index'); 

$endpoint = new EndpointController(); 

$server = new Server(
      null, array('uri' => 'http://api.infinity-mcm.co.uk/api/soap') 
); 


$server->setObject($endpoint); 

$server->handle(); 

和方法的类我控制器,包含所有的功能是

namespace MyProject\Controller; 
class EndpointController 
{ 

    public function addSimpleProducts($products) 
    { 

    } 

} 

现在我希望能够做的就是从这个EndpointController内访问我的产品模型。

所以我尝试这样做:

protected function getProductsTable() 
{ 
    if (!$this->productsTable) { 
     $sm = $this->getServiceLocator(); 
     $this->productsTable= $sm->get('MyProject\Model\ProductsTable'); 
    } 
    return $this->productsTable; 
} 

当我运行此我得到的致命错误EndpointController :: getServiceLocator()是不确定的。

我对Zend 2很新,但在Zend 1中感觉这将是我发展过程中的一个非常小的步骤,我即将解雇zend 2并返回到zend 1甚至切换到symfony 2其中使用简单的教义......

有帮助吗?

回答

3

如果您希望您的控制器可以访问ServiceManager,则需要将ServiceManager注入到其中。

在MVC系统中,由于ServiceManager用于创建控制器实例,所以这种情况几乎会自动发生。这不会发生在您身上,因为您正在使用new创建您的EndpointController

您可能需要通过MVC创建此控制器,或者实例化并配置您自己的ServiceManager实例并将其传递给EndpointController

或者,实例化依赖关系,如ProductTable并将它们设置为您的EndpointController

0

要访问你的服务定位器来实现ServiceLocatorAwareInterface

所以在任何控制器,将需要这一点,你可以做这样的:

namespace MyProject\Controller; 

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

class EndpointController implements ServiceLocatorAwareInterface 
{ 
    protected $sm; 

    public function addSimpleProducts($products) { 

    } 

    /** 
    * Set service locator 
    * 
    * @param ServiceLocatorInterface $serviceLocator 
    */ 
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) { 
     $this->sm = $serviceLocator; 
    } 

    /** 
    * Get service locator 
    * 
    * @return ServiceLocatorInterface 
    */ 
    public function getServiceLocator() { 
     return $this->sm; 
    } 
} 

现在服务管理器将注入本身自动的。然后,您可以使用它像:

$someService = $this->sm->getServiceLocator()->get('someService'); 

如果你正在使用PHP 5.4+可以导入ServiceLocatorAwareTrait,这样你就不必定义getter和setter自己。

class EndpointController implements ServiceLocatorAwareInterface 
{ 
    use Zend\ServiceManager\ServiceLocatorInterface\ServiceLocatorAwareTrait 
+0

我在我的ZF2库中看不到'ServiceLocatorAwareTrait'。这种奢侈品可能还需要特定版本的ZF2? – 2013-03-11 15:44:12

+0

好,所以你说服务管理器应该自动注入自己,但是当我用你建议的改变运行我的代码时,我只是调用一个非对象的成员函数get(),这是$ this-> sm->得到线... – Matthew 2013-03-11 15:58:06

+0

@MarshallHouse,它是2.1.3版本的一部分。见[github](https://github.com/zendframework/zf2/blob/release-2.1.3/library/Zend/ServiceManager/ServiceLocatorAwareTrait.php) – 2013-03-11 16:04:15

相关问题