1

我有一个AbstractTableGateway这样的:

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

}

我想在返回$resultSetinfetchAll方法之前检查一些东西,但是我有很多这种方法,不想在每个方法中放置 if 或 where,想要使函数与类分离,我试图使用 a EventFeatureofTableGateway但zend 缺乏关于它的文档。

你们有什么建议吗?

谢谢

4

1 回答 1

1

我找到了一种方法,

在模型中添加EventFeature构造特征:

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

然后在你的Module.php你需要创建一个SharedEventManager. 那是因为当模型实例化EventFeaturethis时,它会在里面创建一个 的,与 Zend 在 bootstrap 中创建的不同,所以您只需要创建它并附加以下事件:EventManagerEventManager

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
  });
}
于 2018-05-09T16:42:14.817 回答