Symfony: custom filter / hook / eventlistener - how?
I would like to achieve:
- Listen
myController->myAction()
and - call
myService->myModification()
(before) - to filter / modify
$item
(listenToMyFilterBefore
/listenToMyFilterAfter
)
The pseudocode is below. It seems to be a combination of event listening and filtering . What's good practice?
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');
});
}
}
Thank!
source to share
I think the Symfony2 standard events suit your needs: a listener KernelEvents::CONTROLLER
to be called before the controller is executed and KernelEvents::VIEW
to be called after.
Also applicable to FrameworkExtraBundle. This should help you get the element instance before the controller code. Your listener can be selected immediately after ExtraListeners.
The controller is not required to return an instance Response
. If you return Item
then an event will be dispatched KernelEvents::VIEW
. You can process Item
in the appropriate listener and return Response
. Look for FOSRestBundle
and ViewResponseListner
for the same sex.
https://github.com/FriendsOfSymfony/FOSRestBundle
If that's not enough, you can also take the approach AOP
.
http://jmsyst.com/bundles/JMSAopBundle
source to share