我想使用以下代码将 EntityManager 实例传递到我的 Controller 的构造函数中:
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityManager;
class UserController extends Controller
{
public function __construct( EntityManager $entityManager )
{
// do some stuff with the entityManager
}
}
我通过将参数放入 service.yml 文件来执行构造函数注入(inject):
parameters:
# parameter_name: value
services:
# service_name:
# class: AppBundle\Directory\ClassName
# arguments: ["@another_service_name", "plain_value", "%parameter_name%"]
app.user_controller:
class: AppBundle\Controller\UserController
arguments: ['@doctrine.orm.entity_manager']
service.yml 包含在 config.yml 中,当我运行时
php bin/console debug:container app.user_controller
我得到:
Information for Service "app.user_controller"
=============================================
------------------ -------------------------------------
Option Value
------------------ -------------------------------------
Service ID app.user_controller
Class AppBundle\Controller\UserController
Tags -
Public yes
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired no
Autowiring Types -
------------------ -------------------------------------
但是,调用映射到我的 Controller 的路由,我得到:
FatalThrowableError in UserController.php line 17: Type error: Argument 1 passed to AppBundle\Controller\UserController::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /home/michel/Documents/Terminfinder/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php on line 202
我想不通,为什么 EntityManager 没有被注入(inject)?
最佳答案
使用基类时Controller.php
Container
通常由 ControllerResolver
中的框架自动连接.
基本上,您是在试图混淆事物的实际运作方式。
要解决您的问题,您基本上有两种解决方案:
- 不要尝试注入(inject)依赖项,而是直接从您的操作/方法中的容器中获取它。
公共(public)函数列表用户(请求 $request)
{
$em = $this->container->get('doctrine.orm.entity_manager');
}
- 手动创建 Controller 但不扩展 Controller 基类;和 set ip up as a service
为了在这一点上更进一步,有些人会建议不要使用 Symfony 提供的默认 Controller 。
虽然我完全理解他们的观点,但我在这个问题上稍微温和一些。
仅注入(inject)所需的依赖项背后的想法是避免并迫使人们拥有瘦 Controller ,这是一件好事。
但是,通过一些自动确定,使用现有的快捷方式要简单得多。
Controller
/Action
只不过是 Views
和 Domain
之间的粘合剂/模型
。
使用 ContainerAware
工具防止自己在 Controller
中做太多事情。
Controller
可以丢弃,而不会在您的系统中产生业务更改。
关于php - Symfony Controller 构造函数注入(inject)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779618/