symfony - Share a method with all controllers : Best practice -
If the template has to use it for output then the best method would be to have a custom TwigExtension Services In this way you can use your code in any template using If it was placed in a block in a parent template, .. By then you will run on every page until you override the block your child c lass
I am developing a notification system in symfony2 and need to get notifications for every page I run I
The trivial solution is to copy the contents of the function in each controller and calls the function with $ this .
How can I make the notification function accessible for each controller? I have heard that setting up the controller as a service is bad behavior, what is the best practice? TwigFunction Use and then call in a base / layout / extended template like that.
Namespace Acme \ NotificationBundle \ Twig; Use Acme \ NotificationBundle \ Provider \ NotificationProviderInterface; Class AcmeNotificationExtension \ Twig_Extension {protected $ container; Protected $ information provider; Public Function __ Composition (Container Interface $ Container, Notification Provider, Interface $ Notification Provider) {$ this- & gt; Notification provider = $ Notification Provider; } Public Function getFunctions () {Return Array (New \ Twig_SimpleFunction ('acme_render_notifications', array ($ this, 'render notifications')),); } Public function render notifications ($ template = 'default: template.html.twig') {$ notifications = $ this- & gt; Notification provider- & gt; GetCurrentNotifications (); // or whatever method your notifications provide, that $ $ -> container- & gt; Receive ('Templates') - & gt; Render ($ template, array ('notifications' = & gt; $ notification)); } Public event getName () {return 'acme_notification_extension'; }}
Parameter: acme.twig.notification_extension.class: Axes \ Notification bundle \ Excise Notification Services: acme.twig.notification_extension: class :% Acme.twig.notification_extension.class% Arguments: - @service_container - @ acme.provider.notifcation // or what is the name of your notification provider service: - {name: twig.extension}
acme_render_notifications () (with default template) or
acme_render_notifications ('AcmeOtherBundle: Notifications: in_depth.html.twig) Call on He will be able to run. ') (with a different template if necessary) and your controller is not touched.
{% block notifications%} {{acme_render_notifications ()}} {% endblock notifications%}
Comments
Post a Comment