[Symfony 2.7] récupération instance doctrine dans le constructeur d'un contrôleur
Bonjour,
J'ai un petit souci avec l'initialisation d'une variable.
J'ai un controleur :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
namespace SB\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use Mie\FrontendBundle\Entity\Product;
class FrontendController extends Controller
{
protected $em;
public function __construct(EntityManager $entityManager = null)
{
$this->em = $this->getDoctrine()->getManager(); //--->TEST 1
$this->em = $entityManager; //--->TEST2
}
public function dispatchUrl(Request $request)
{
$this->em = $this->getDoctrine()->getManager(); //--->TEST 3
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$this->em->persist($product);
$this->em->flush();
die();
}
} |
j'ai un fichier service.yml dans lequel je configure le passage du service doctrine à la class FrontendController
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| parameters:
mie.frontend.controller.frontend.class: Mie\FrontendBundle\Controller\FrontendController
services:
# ---> ESSAI 1
mie.frontend.controller:
class: "%mie.frontend.controller.frontend.class%"
arguments:
- "@doctrine.orm.entity_manager"
# ---> ESSAI 2
mie.frontend.controller:
class: "%mie.frontend.controller.frontend.class%"
arguments: [ @doctrine.orm.entity_manager ]
# ---> ESSAI 3
# mie.frontend.controller:
# class: "%mie.frontend.controller.frontend.class%"
# calls:
# - [setEntityManager, ["@doctrine.orm.entity_manager"]] |
Le TEST 1 ne fonctionne pas
Le TEST 2 avec les ESSAI 1,2,3 (services.yml) ne fonctionne pas
Le TEST 3 fonctionne
Avec le TEST 1, j'obtiens l'erreur
Error: Call to a member function has() on null
in vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\Controller.php at line 291
Avec le TEST 2
$entityManager (l'argument de la fonction __construct) est null
Je n'ai pas trouvé de contre-indication quant à l'initialisation, dans le controller, d'une variable contenant une instance de l'entitymanager.
Avec Symfony2.3, le test 2 fonctionnait, il me semble.
Est-ce qu'il y a quelque chose d'autre à configurer au niveau du service doctrine ?
merci,
Phil