2017-03-05 105 views
0

我是ZF2的新手。經過幾天試圖找出所有這些東西應該如何工作,我無法弄清楚如何從服務調用TableGateway模型。Zend Framework 2調用TableGateway服務

所以我有控制器:

class SubscriberController extends AbstractActionController 
{ 
/** 
* @var \Subscriber\Service\SubscriberServiceInterface 
*/ 
private $subscriberService; 

/** 
* @param $subscriberService 
*/ 
public function __construct(SubscriberServiceInterface $subscriberService) 
{ 
    $this->subscriberService = $subscriberService; 
} 

Factroy此控制器:

class SubscriberControllerFactory implements FactoryInterface 
{ 
/** 
* Returns ArchiveController instance. 
* 
* @param ServiceLocatorInterface $serviceLocator 
* @return SubscriberController 
* @override 
**/ 
public function createService(ServiceLocatorInterface $serviceLocator) 
{ 
    $sm = $serviceLocator->getServiceLocator(); 

    return new SubscriberController(
     $sm->get('Subscriber\Service\SubscriberServiceInterface') 
    ); 
} 

一些SubscriberTable:

class SubscriberTable 
{ 
protected $tableGateway; 

public function __construct(TableGateway $tableGateway) 
{ 
    $this->tableGateway = $tableGateway; 
} 

public function fetchAll() 
{ 
    $resultSet = $this->tableGateway->select(); 
    return $resultSet; 
} 

和服務中,我想SubscriberTable實例,使一些邏輯。但我無法弄清楚如何在SubscriberService中調用此實例,併爲SubscriberTable設置DbAdapter

回答

1
First implement servicelocator interface and define get and set locator functions to your service like this. 

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

    class Yourservice implements ServiceLocatorAwareInterface{ 

    function test(){ 
     $this->getSubscriberTable->fetchAll(); // call to subscriber table functions 
    }  

    /** 
    * @table gateway Call 
    **/ 
    public function getSubscriberTable() 
    { 
     if (!$this->SubscriberTable) { 
      $sm = $this->getServiceLocator(); 
      $this->SubscriberTable = $sm->get('Application\Model\SubscriberTable'); 
     } 
     return $this->SubscriberTable; 
    } 

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

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

希望它能幫助你。