Search code examples
phpzend-framework2event-driventablegateway

How to perform a pre select in zf2


I have a AbstractTableGateway like this:

class FundsTable extends AbstractTableGateway
{

protected $table = 'tb_funds';

public function __construct(AdapterInterface $adapter)
{
    $this->adapter = $adapter;
    $this->resultSetPrototype = new HydratingResultSet(new FundsHydrator(), new Fund());
    $this->initialize();
}

public function fetchAll($year)
{
    $select = new Select(array("f" => $this->table));
    $resultSet = $this->selectWith($select);
    $resultSet->initialize($resultSet->toArray());
    return $resultSet;
}

}

And i would like to check something before return the $resultSet in fetchAll method, but i have a lot of this methods and dont want to put a if or a where in each of them, would like to make a function uncoupled of the class, i tried to use a EventFeature of TableGateway but the zend is lack of documentation about that.

Did you guys have any suggestions?

Thanks


Solution

  • I found a way to do that,

    In model jut add the EventFeature feature on construct:

    $this->featureSet = new FeatureSet();
    $this->featureSet->addFeature(new EventFeature());
    

    And then in your Module.php you ll need to create a SharedEventManager. That's because when the model instantiate the EventFeature this create a new EventManager inside that, different from EventManager that the Zend create in bootstrap, so you just need to create that and attach a following event:

    public function onBootstrap(MvcEvent $event)
    {
      $eventManager = $event->getApplication()->getEventManager();
      $sharedEventManager = $eventManager->getSharedManager();
    
      $sharedEventManager->attach(
            'Zend\Db\TableGateway\TableGateway',
            EventFeature::EVENT_PRE_SELECT,
            function (EventFeature\TableGatewayEvent $e) {
                //Do stuff here or call some method
      });
    }