Symfony 传递给控制器的参数必须是ContainerInterface的实例,即给定的AppDevDebBugProjectContainer实例

Symfony 传递给控制器的参数必须是ContainerInterface的实例,即给定的AppDevDebBugProjectContainer实例,symfony,dependency-injection,sonata,Symfony,Dependency Injection,Sonata,为什么我会有这个错误 可捕获的致命错误:传递给Application\Sonata\ProductBundle\Controller\ProductAdminController::\uu construct()的参数1必须是ContainerInterface的实例,即给定的AppDevDebBugProjectContainer实例 这是我的服务。yml: services: product_admin_controller: class: Application\Son

为什么我会有这个错误

可捕获的致命错误:传递给Application\Sonata\ProductBundle\Controller\ProductAdminController::\uu construct()的参数1必须是ContainerInterface的实例,即给定的AppDevDebBugProjectContainer实例

这是我的服务。yml:

services:
    product_admin_controller:
      class: Application\Sonata\ProductBundle\Controller\ProductAdminController
      arguments: ["@service_container"]
      tags:
            - { name: doctrine.event_listener, event: postLoad, connection: default  }
和我的控制器:

class ProductAdminController extends Controller
{
    protected $container;

    public function __construct(\ContainerInterface $container)
    {
        $this->container = $container;
    }
}

首先,为什么要尝试使用u constract()?相反,您必须使用setContainer()方法,该方法将ContainerInterface$container作为参数,它应该如下所示:

<?php
...
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;

...
class YourClass extends Controller
{

    public function setContainer(ContainerInterface $container = null)
    {
        // your stuff
    }
}

您必须通过“calls”选项注入容器,而不是作为参数,我认为:

services:
    product_admin_controller:
      class: Application\Sonata\ProductBundle\Controller\ProductAdminController
      arguments: ["@another_service_you_need"]
      tags:
            - { name: doctrine.event_listener, event: postLoad, connection: default  }
      calls:
            -   [ setContainer,["@service_container"] ]

另外,不要忘记在侦听器类中创建公共方法“setContainer()”。

这似乎是
Symfony
的经典控制器和控制器即服务概念的混合。为什么您要扩展
控制器
并通过
\uu构造
传递
容器
?这是一个名称空间问题。使用Symfony\Component\DependencyInjection\ContainerInterface__构造(ContainerInterface)。你真的应该使用ContainerWare接口。更好的是,注入你的特定依赖项,而不是完整的容器。感谢大家的帮助。主要目标是覆盖orm产品类,并使用mongodb odm驱动的变体对象对其进行扩展。我尝试并重现了这个()因此,第一次尝试是注入EntityManager(),但我无法做到没有错误,所以我尝试了()我使用了_构造()函数,因为我要进行的mongoDB«扩展»是一种常规行为。我希望mongoDB变体对象始终扩展mysql产品对象。到目前为止,我成功地通过了EntityManager(按照事先计划)通过服务调用函数,但是,由于类被调用了两次,第一次,我的
EntityManager$em
是一个对象,第二次它是
null
…我不明白为什么?因为这是最好的方法吗?对不起,但我认为“因为mongoDB«扩展»”没有任何解释。我仍然认为您不必将服务容器或实体管理器注入控制器。