首页 文章

传递给控制器的参数必须是ContainerInterface的实例,给出appDevDebugProjectContainer的实例

提问于
浏览
4

为什么我有这个错误?

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

这是我的services.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;
    }
}

2 回答

  • 1

    你必须通过“调用”选项注入容器,而不是我认为的参数:

    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()” .

  • 3

    首先,你为什么要尝试使用__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
        }
    }
    

    第二个问题:你需要将容器注入控制器?您可以使用$ this-> get('')语句调用任何服务,而不是直接调用容器 .

相关问题