Oph*_*hus 5 dependency-injection symfony sonata
为什么会出现此错误?
可捕获的致命错误:传递给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 }
Run Code Online (Sandbox Code Playgroud)
而我的控制器:
class ProductAdminController extends Controller
{
protected $container;
public function __construct(\ContainerInterface $container)
{
$this->container = $container;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 1
首先,为什么要尝试使用 __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
}
}
Run Code Online (Sandbox Code Playgroud)
第二个问题:为什么需要将容器注入到控制器中?您可以使用 $this->get('{service_id}') 语句调用任何服务,而不是直接调用容器。
| 归档时间: |
|
| 查看次数: |
5825 次 |
| 最近记录: |