My web application as a topbar where i need to display the number of unreaded messages. Each User entity as an association with Message (many-to-many). Showing the total number of messages (for a given user) would be simple:
class User
{
/*
* @ORM\ManyToMany(targetEntity="Message", invertedBy="users")
*/
private $messages;
}
In Twig:
Total messages: {{ app.user.messages|length }}.
But what if i need to count only new messages? Assuming my repository has a getNewMessages(User $user) method, how can assign this value globally to use in every template?
I know about Twig globals, but i don’t know where i’m supposed to put the relevant code:
$twig = new Twig_Environment($loader);
$twig->addGlobal('text', new Text());
{{ text.lipsum(40) }}
I would register an event listener that occurs on every request, probably the
kernel.requestevent. In the listener you can check for a logged in user, and if so update a session variable with the new message count. You can then access this session variable in twig withapp.session.msg_countThis also has the advantage that you can cache it and only update under certain conditions, to avoid querying on every request.