如何在zf2中执行预选择

时间:2018-05-08 20:30:07

标签: php zend-framework2 event-driven tablegateway

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

}

我想在$resultSet方法中返回fetchAll之前检查一下,但我有很多这样的方法,并且不想在每个方法中放置if或a where,为了使一个函数解耦为类,我试图使用EventFeature TableGateway,但zend缺乏关于它的文档。

你们有什么建议吗?

由于

1 个答案:

答案 0 :(得分:1)

我找到了一种方法,

在模型jut中,在构造中添加EventFeature功能:

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

然后在Module.php中,您需要创建一个SharedEventManager。这是因为当模型实例化EventFeature时,会在其中创建一个 new EventManager,与Zend在bootstrap中创建的EventManager不同,所以你只需要创建并附加以下事件:

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