容器在Symfony 2中使用一个简单的控制器类内部不起作用

时间:2015-05-21 10:26:22

标签: php symfony dependency-injection

我的错误:

use Symfony\Component\DependencyInjection\ContainerInterface;
/**
 * @Route(service="srv_grafica")
 */
class grafica
{
    private $container, $conn, $bdnmgi;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->conn = $this->getConn();
        $this->bdnmgi = $this->getBd();
    }

    public function getConn(){
        return $this->container->get('database_connection');
    }
    public function getBd(){
        return $this->container->get('security.context')->getToken()->getUser()->getAdministracion()->getNombreEsquemamgi();
    }
}

我的班级grafica:

services:
    srv_grafica:
        class: Agc\ManagerBundle\Lib\grafica
        arguments:
            - '@service_container'

\ ManagerBundle \资源\配置\ services.yml

class DefaultController extends Controller
{
    public function dashboardAction(Request $peticion)
    {
        $em = $this->getDoctrine()->getManager('customer_1');
        $user= $this->get('security.context')->getToken()->getUser();
        $esquema = $user->getAdministracion()->getNombreEsquemamgi();
        var_dump($esquema);
        $grafica = new grafica();
    }
}

我的DefaultController:


1 个答案:

答案 0 :(得分:1)

您正在致电

$grafica = new grafica();

此类在构造函数中需要ContainerInterface参数。要解决此问题,您需要将此行更改为:

$grafica = new grafica($this->container);

请注意,您的代码不是以Symfony方式编写的。要正确执行此操作,您应该定义grafica class as a service并且不应该注入整个容器,只需注入所需的类