1

I'm creating a menu system using the Tree Doctrine extenion and I want to create a Twig extension to display the menu based on the requested parent node e.g. {% display_menu(side_menu) %}. This function will be in the base twig template (i.e. the menu is on every page of the website).

As I'll be storing the Menu structure with Doctrine, I thought I'd need to access the MenuRepository within the Twig extension so the first problem I came across was getting an Entity Manager into it. When looking for a solution, a few people have said that this is bad practice, which makes sense as a Twig extension is part of the View.

So although there is a solution (linked in similar questions) to my problem, my question is, is there a way I can accomplish it using good practice? Or is there a better way of doing it in the first place?

Robin
  • 412
  • 7
  • 17

1 Answers1

2

Making entities aware of any services — including entity managers — is a bad practice. There's nothing wrong about injecting an EM into a Twig extension. Although, I'd rather inject a model manager to a Twig extension, so that the extension is not aware of the persistence layer — it's the job of the manager layer.

So, I'd have MenuManager that's aware of repositores/entity managers and inject it to an extension.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • Thank you for the advice. I'll use the accepted answer from [here](http://stackoverflow.com/questions/8450465/fetching-data-through-a-custom-repository-in-a-twig-extension?rq=1) in this case. – Robin Feb 27 '13 at 09:45