0

我是ZF2的新手。经过几天试图弄清楚所有这些东西应该如何工作后,我无法弄清楚我应该如何从服务中调用 TableGateway 模型。

所以我有控制器:

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

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

此控制器的工厂:

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

一些订阅者表:

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

4

1 回答 1

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

希望它会帮助你。

于 2017-03-10T10:17:11.680 回答