我一直在試圖撥打Entity Manager
在構造函數中:如何在構造函數中調用實體管理器?
function __construct()
{
$this->getDoctrine()->getEntityManager();
...
但是,正如我在這個答案已經看到:Stackoverflow question,它無法做到的。
所以我想知道是否有辦法實現它,因爲我必須經常調用它,並且想在獲取存儲庫之後在構造函數中執行一些操作。
編輯:
我試着@MKhalidJunaid答案:
//src/MSD/HomeBundle/Resources/config/services.yml
services:
imageTransController.custom.service:
class: MSD\HomeBundle\Controller\ImageTransController
arguments:
EntityManager: "@doctrine.orm.entity_manager"
-
//app/config/config.php
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: doctrine_extensions.yml }
- { resource: "@MSDHomeBundle/Resources/config/services.yml" }
-
//src/MSD/HomeBundle/Controller/ImageTransController.php
namespace MSD\HomeBundle\Controller;
use Doctrine\ORM\EntityManager;
use MSD\HomeBundle\Entity\Imagen as Imagen;
use MSD\HomeBundle\Controller\HomeController as HomeController;
class ImageTransController extends HomeController
{
protected $em ;
function __construct(EntityManager $entityManager)
{
...
,但我「M收到此錯誤:
Catchable Fatal Error: Catchable Fatal Error: Argument 1 passed to MSD\HomeBundle\Controller\ImageTransController::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /home/manolo/MiServer/itransformer/app/cache/dev/jms_diextra/controller_injectors/MSDHomeBundleControllerImageTransController.php on line 13 and defined in /home/manolo/MiServer/itransformer/src/MSD/HomeBundle/Controller/ImageTransController.php line 38 (500 Internal Server Error)
新嘗試:
我也試圖與@praxmatig答案:
//services.yml
parameters:
msd.controller.imagetrans.class: MSD\HomeBundle\Controller\ImageTransController
services:
msd.imagetrans.controller:
class: "%msd.controller.imagetrans.class%"
arguments: [ @doctrine.orm.entity_manager ]
-
//ImageTransController.php
namespace MSD\HomeBundle\Controller;
use Doctrine\ORM\EntityManager;
class ImageTransController
{
protected $em ;
function __construct(EntityManager $em)
{
$this->em = $em;
}
...
-
//routing.yml
msd_home_cambiardimensiones:
pattern: /cambiardimensiones
defaults: { _controller: MSDHomeBundle:msd.imagetrans.controller:cambiardimensionesAction }
,但我得到這個錯誤:
Unable to find controller "MSDHomeBundle:msd.imagetrans.controller" - class "MSD\HomeBundle\Controller\msd.imagetrans.controllerController" does not exist. (500 Internal Server Error)
@MKhalidJunaid - 如果'EntityManager'被構造之後注入,我怎麼可能通過'EntityManager'作爲構造函數中的參數?你能發表一個詳細的答案嗎? – Manolo
這是什麼依賴注入是因爲它是在構造函數調用後注入以訪問構造函數中的實體管理器,您需要創建一個服務並將其作爲參數傳遞它看到我的答案,它會給你一個想法 –