我一直在zend 1开发一个项目,但决定转到zend 2来利用事件等优势。
我最初的问题是,我似乎无法找到有关如何以我需要的方式使用模型的任何教程。
我所拥有的是一个Api控制器,它被路由到/ api / soap
这个soap端点加载一个类,该类包含我想通过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的程度其简单易用的原则......
帮助?
答案 0 :(得分:3)
如果您希望控制器可以访问ServiceManager,则需要将ServiceManager注入其中。
在MVC系统中,这几乎会自动发生,因为ServiceManager用于创建Controller的实例。当您使用EndpointController
创建new
时,这种情况不会发生。
您需要通过MVC创建此控制器,或者实例化并配置您自己的ServiceManager实例并将其传递给EndpointController
。
或者,实例化依赖项,例如ProductTable
并将它们设置为EndpointController
。
答案 1 :(得分: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