symfony - How can I fetch a value from the DB and display it in all templates? -


Assume that I have a user and a message my Symfony2 The unit is an app with a one to the relationship between the two organizations, so that the user can have more than one message, and I display the number of unread messages in this kind of main navigation

  • Message (6)
  • My Profile
  • p> Where (6) unread messages To get this amount of number per user controller independently, I can think of defining the user unit method:
      public function getUnreadMessagesCount () {$ unreadMessagesCount = 0; Foreign exchange ($ this-> message as $ message) {if ($ message-> Unread ()) {$ unreadMessagesCount ++; }}}   

    and call it in my menu.html.twig

      {% set umc = app.user }. GetUnreadMessagesCount ()%} {% if umc & gt; 0%} ({{umc}}} {% endif%}   

    But for performance reasons, I would like to completely avoid looping through message messages just to check it For whether it is unread or not, I prefer to get it through DQL call (and keep this fame in UserRepository class)

      $ Query = $ em- & gt; createQuery (select "select"). D. WHERE M.Rread = Truth and U.ID =: UID ");   

    But the apaic use of the Repository methods or the use of the Entity Manager (or theory) in the unit sections Practicing is to do.

    I thought about bringing value to the service and inject it into my institution. But this is not recommended to inject the services in signals. < P> then get this value and come in all the templates What is a legal way to extract (It can be done without any unit methods, for example, controlling the value in all)

    I used another solution to get data from a repository.

    First, define the service:

      ## bundle / resource / config / services.yml in services: YOUR_BUNDLE .twig.NAME_OF_THE_EXTENSION: Category: Your \ Bundle \ Toggle \ CLASSNAME Argument: - @service_container Tags: - {name: twig.extension}   

    Then define the Tivig extension class:

      # yOUR_BUNDLE / tweed / CLASSNAME.php    

  • Comments

    Popular posts from this blog

    Verilog Error: output or inout port "Q" must be connected to a structural net expression -

    jasper reports - How to center align barcode using jasperreports and barcode4j -

    c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -