如何在控制器外使用 serviceLocator

How do I use the serviceLocator outside of the controller

如何在模型中使用 Zend Framework 服务定位器?我有一个 class,我想在其中使用 Table 网关模型。我遵循了 Album 示例并希望访问控制器外部的 table。但是,如果我将代码从控制器复制并粘贴到我需要的 class 中,我会收到错误消息(未定义的方法:getServiceLocator())。我如何在控制器外使用这个 'class'?

最后我想访问“class 相册Table”中的功能而不是控制器(在本例中是另一个 class)。谢谢。

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');

如果您想在任何 class 中使用 ServiceLocator,只需实施 ServiceLocatorAwareInterface。例如:

class SomeClass implements ServiceLocatorAwareInterface
{
    protected $serviceLocator;

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

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

ZendFramework2 会自动将 ServiceLocator 实例注入您的 class。 详细了解 ServiceManager here