Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Circular reference

Tags:

symfony

Probably I have a problem with a loop in template.

services:
    twig_menu:
        class: Cms\PageBundle\Twig\Menu
        arguments: ['@doctrine.orm.entity_manager', "@templating"]

Code php:

namespace Cms\PageBundle\Twig;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Templating\EngineInterface;
class Menu {
    protected $em, $templating;
    public function __construct(EntityManager $em, EngineInterface $templating){
        $this->em = $em;
        $this->templating=$templating;
    }
    public function show($typ){
        $menu=$this->em->getRepository("CmsAdminBundle:Menu")->findBy(array('type_id'=>$typ));
        return $this->templating->render("menu.html.twig", array('links'=>$menu));
    }
}

Template:

<ul>
    {% for link in links %}
        <li><a href="{{ link.href }}">{{ link.name }}</a></li>
    {% endfor %}
</ul>

When I cleared cache on the first refresh it is ok, next I get this error:

Circular reference detected for service "templating", path: "templating -> twig -> twig_menu".

like image 210
viko Avatar asked Mar 21 '26 08:03

viko


2 Answers

templating needs twig, twig needs twig_menu and twig_menu needs templating. Hence your circular reference problem. It might be because you're in dev mode, where Twig has a lot more dependencies, because of the profiler.

Fabien Potencier himself has answered this problem on GitHub by saying "Just inject the service container and get Twig from that". It's a quick and dirty solution, but it should work without any serious penalties.

But because injecting the service container is a code smell, you might want to avoid it. The deeper (more correct) solution is to refactor so that twig doesn't depend on twig_menu, but without knowing your entire project, it's hard to say how you could do that.

like image 77
Dan Blows Avatar answered Mar 24 '26 19:03

Dan Blows


Inject the twig service, rather than the templating service. @twig is the service name.

like image 41
axelvnk Avatar answered Mar 24 '26 18:03

axelvnk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!