如何在模型中使用Zend Framework Service Locator?我有一个类,我想使用表网关模型 . 我已经按照Album示例,并希望访问控制器外部的表 . 但是,如果我将控制器中的代码复制并粘贴到我需要的类中,则会出现错误(未定义的方法:getServiceLocator()) . 如何在控制器外部使用此“类”?
最后,我想访问“class AlbumTable”中的函数,而不是控制器(在本例中是另一个类) . 谢谢 .
class Calendar implements ServiceLocatorAwareInterface{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
/*
* Create Calendar Sync Table
*/
public function getCalendarSyncTable()
{
if (!$this->calendarSyncTable) {
$sm = $this->getServiceLocator();
$this->calendarSyncTable = $sm->get('Pro\Model\CalendarSync\CalendarSyncTable');
}
return $this->calendarSyncTable;
}
需要改变我在控制器中调用它的方式
$calendar = $this->getServiceLocator()>get('Pro\Model\GoogleCalendar\Calendar');
1 回答
如果要在任何类中使用ServiceLocator,只需实现
ServiceLocatorAwareInterface
. 例如:ZendFramework2将自动为您的类注入ServiceLocator实例 . 了解有关ServiceManager的更多信息here