0
votes

I use symfony2 (2.6) and I have class to global variable to twig. For Example, class menu:

namespace Cms\PageBundle\Twig;

use Doctrine\ORM\EntityManager;
class Menu {
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
    public function show(){
       /******/
    }
}

and services.yml

services:
    class_menu:
        class: Cms\PageBundle\Twig\Menu
        arguments: ['@doctrine.orm.entity_manager']

    twig_menu:
        class: Cms\PageBundle\Twig\Menu

See:

ContextErrorException in Menu.php line 9: Catchable Fatal Error: Argument 1 passed to Cms\PageBundle\Twig\Menu::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /home/cms/public_html/app/cache/dev/appDevDebugProjectContainer.php on line 3834 and defined

General, any class (outside) have problem with the constructor and (argument) doctrine. Why?

Symfony2 getdoctrine outside of Model/Controller

1
try without ' arguments: [@doctrine.orm.entity_manager]Matteo
@Matteo: No change. I tried with ", ' and whitout it. I don't understand it.viko
try removing the type on the costructor as public function __construct( $em)Matteo
Ok. No changes. Clear cache too.viko
Where is: function __construct($em), see: Warning: Missing argument 1 for Cms\PageBundle\Twig\Menu::__construct(), called in /home/cms/public_html/app/cache/dev/appDevDebugProjectContainer.php on line 3834 and definedviko

1 Answers

1
votes

This error is totally expected. Symfony2 expects to create service instance by invoking the __construct constructor. If you want to keep the single class in play, you will need to remove that __construct and use setter dependency injection instead.

There is an official documentation on this: Optional Dependencies: Setter Injection

Basically, you do not pass the EntityManager instance during the creation of an service instance but rather "set it later".

Hope this helps.

Update:

If you fallback to your original solution, make sure you pass EntityManager in both instances:

services:
    class_menu:
        class: Cms\PageBundle\Twig\Menu
        arguments: ['@doctrine.orm.entity_manager']

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