gpt4 book ai didi

php - Symfony:自定义过滤器/ Hook /事件监听器 - 怎么做?

转载 作者:搜寻专家 更新时间:2023-10-31 21:08:38 24 4
gpt4 key购买 nike

我想实现:

  • 听取 myController->myAction()
  • 调用myService->myModification()(之前)
  • 过滤/修改$item (listenToMyFilterBefore/listenToMyFilterAfter)

下面的伪代码。似乎是 event listening 的混合体和 filtering .什么是好的做法?

class myController() {
public function myAction() {
$item = new Item();
$item = registerFilter('listenToMyFilterBefore', $item); // possibility to prepare before

// ... some modification ...

$item = registerFilter('listenToMyFilterAfter', $item); // possibility to modify after

// ...
}
}

class myService {
public function myModification() {
// listen to "myController->myAction"

$item = filter('listenToMyFilterBefore', function($item) {
$item->setLockMe(true);
});

$item = filter('listenToMyFilterBefore', function($item) {
$item->setLockMe(false);
$item->setSomeValue('myValue');
});
}
}

谢谢!

最佳答案

我认为标准的 Symfony2 事件适合您的需求:监听器 KernelEvents::CONTROLLER 在 Controller 执行之前调用,KernelEvents::VIEW 在之后调用。

也适用于 FrameworkExtraBundle。它应该可以帮助您在 Controller 代码之前获取 Item 的实例。您的监听器可以在 ExtraListeners 之后立即获取。

Controller 没有义务返回 Response 实例。如果您将返回 Item,那么将调度 KernelEvents::VIEW 事件。您可以在相应的监听器中处理 Item 并返回 Response。寻找类似楼层的 FOSRestBundleViewResponseListnerhttps://github.com/FriendsOfSymfony/FOSRestBundle

如果这还不够,您还可以应用 AOP 方法。 http://jmsyst.com/bundles/JMSAopBundle

关于php - Symfony:自定义过滤器/ Hook /事件监听器 - 怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27230173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com