【问题标题】:container doesnt work using inside of a simple controller class in Symfony 2在 Symfony 2 中的简单控制器类内部使用容器不起作用
【发布时间】:2015-05-21 10:26:21
【问题描述】:

我的错误:

> ContextErrorException: Catchable Fatal Error: Argument 1 passed to
> Agc\ManagerBundle\Lib\grafica::__construct() must implement interface
> Symfony\Component\DependencyInjection\ContainerInterface, none given,
> called in
> C:\wamp\www\galileo\src\Agc\BackendBundle\Controller\DefaultController.php
> on line 20 and defined in
> C:\wamp\www\galileo\src\Agc\ManagerBundle\Lib\grafica.php line 10

我的班级涂鸦:

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();
    }
}

\ManagerBundle\Resources\config\services.yml

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

我的默认控制器:

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();
    }
}

【问题讨论】:

    标签: php symfony dependency-injection


    【解决方案1】:

    你在打电话

    $grafica = new grafica();
    

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

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

    请注意,您的代码不是以 Symfony 方式编写的。要正确地做到这一点,你应该定义你的 grafica class as a service 并且你不应该注入整个容器,只注入你需要的类

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多