我想实现:
- 听
myController->myAction()
和 - 呼叫
myService->myModification()
(之前) - 过滤/修改
$item
(listenToMyFilterBefore
/listenToMyFilterAfter
)
下面的伪代码。似乎是事件侦听和过滤的混合体。什么是好的做法?
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
在控制器执行之前调用,KernelEvents::VIEW
在控制器执行之前调用。
也适用于 FrameworkExtraBundle。它应该可以帮助您在控制器代码之前获取 Item 的实例。您的侦听器可以在 ExtraListeners 之后立即获取。
控制器没有义务返回Response
实例。如果您将返回Item
则KernelEvents::VIEW
事件将被发送。您可以在相应的侦听器中处理Item
并返回Response
。寻找FOSRestBundle
,ViewResponseListner
寻找类似的楼层。https://github.com/FriendsOfSymfony/FOSRestBundle
如果这还不够,您也可以申请AOP
方法。http://jmsyst.com/bundles/JMSAopBundle