symfony - Share a method with all controllers : Best practice -



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?

If the template has to use it for output then the best method would be to have a custom TwigFunction Use and then call in a base / layout / extended template like that.

TwigExtension

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

Services

  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}   

In this way you can use your code in any template using 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.

If it was placed in a block in a parent template,

  {% block notifications%} {{acme_render_notifications ()}} {% endblock notifications%}   

.. By then you will run on every page until you override the block your child c lass

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -