Zend Framework 2 call TableGateway in Service

76 Views Asked by At

I'm new to ZF2. After few days of trying to figure out how all this stuff should work I was unable to figure out how should I call TableGateway Model from Service.

So I have Controller:

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

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

Factroy for this Controller:

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

Some SubscriberTable:

class SubscriberTable
{
protected $tableGateway;

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

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

And Service in which I want to get SubscriberTable instance and make some logic. But I can't figure out how should I call this instance in SubscriberService and set the DbAdapter for SubscriberTable

1

There are 1 best solutions below

0
Amiya Ranjan On
    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;
    }
}

Hope it will help you.