2017-03-05 4 views
0

私はZF2を初めて使いました。このようなことがどのように機能するかを理解しようと数日した後、私はTableGatewayモデルをサービスからどのように呼び出すべきかを理解することができませんでした。このコントローラのZend Framework 2呼び出しTableGateway inサービス

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:私はSubscriberTableインスタンスを取得し、したいで

class SubscriberTable 
{ 
protected $tableGateway; 

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

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

とサービスいくつかの論理。しかし、私はSubscriberServiceでこのインスタンスを呼び出す必要があります方法を見つけ出すとSubscriberTable

答えて

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; 
    } 
} 

ためDbAdapterを設定することはできません、それはあなたを助けることを願っています。

関連する問題