【问题标题】:Symfony 2.8: Can't manage to use container in custom classSymfony 2.8:无法在自定义类中使用容器
【发布时间】:2016-03-24 10:15:49
【问题描述】:

我想在我创建的自定义类中使用 $this->container->get。 我已经阅读并发现我应该在构造函数中使用 ContainerInterface,我这样做了,但我仍然收到此错误:

错误:在非对象上调用成员函数 get()

代码如下:

MyClass.php

namespace path\to\MyClass;

use Symfony\Component\DependencyInjection\ContainerInterface;

class MyClass {

    private $container;
    public $user_id;

    public function __contruct(ContainerInterface $container) {

        $this->container = $container;
        $this->user_id = $user_id;

        return $this;
    }

    /**
     * @param string $data Some data
     * @return array A response
     */
    public function generatePDF($data)
    {
        // Create the folders if needed
        $pdf_folder =  __DIR__.'/../../../../web/pdf/'.$this->user_id.'/';

        if(!file_exists($pdf_folder))
            mkdir($pdf_folder, 0755, TRUE);

        $file_id = "abc1";

        // Set the file name
        $file = $pdf_folder.$file_id.'.pdf';

        // Remove the file if it exists to prevent errors
        if(file_exists($file)) {
            unlink($file);
        }

        // Generate the PDF
        $this->container->get('knp_snappy.pdf')->generateFromHtml(
            $this->renderView(
                'StrimeGlobalBundle:PDF:invoice.html.twig',
                $data
            ),
            $file
        );
    }
}

你们知道可能是什么问题吗?

感谢您的帮助。

【问题讨论】:

  • 你是如何注入容器的?为什么不直接注入 knp_snappy.pdf 呢?
  • 嗨@JimL,现在这就是我的班级的样子。您如何建议将容器注入其中?您将如何直接注入 KNP?感谢您的帮助。
  • 嗨@JimL,在你的帮助和 rouflak 的帮助下,我设法让它工作了。谢谢。
  • 太棒了 :) 他所说的注入您需要推荐的实际服务是绝对正确的。它使测试您的服务/类变得更加容易
  • 你是对的。我花了一些时间才弄清楚如何让它工作,但多亏了你们两个,我现在明白了其中的逻辑。再次感谢。 :o)

标签: php class symfony service containers


【解决方案1】:

您需要在 Symfony 配置中将您的类声明为服务。

请查看Symfony service container page

下面是在构造函数中注入容器的解释:

# services.yml
services:
    app.my_class:
        class: TheBundle\Service\MyClass
        arguments: ['@service_container']

或者正如 JimL 在评论中所说,你可以注入你需要的服务(这是推荐的):

class MyClass
{
    private $pdfService;
    public function __construct(\Your\Service\Namespace\Class $pdfService)
    {
        $this->pdfService = $pdfService;
    }

    // ...
}

在你的 service.yml 文件中

# services.yml
services:
    app.my_class:
        class: TheBundle\Service\MyClass
        arguments: ['@knp_snappy.pdf']

容器也可以注入一个setter。见this link

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    除非您“注入”它,否则您的班级无法“看到”任何服务(包括容器)。在 YourCustomBundle/Resources/config/services.xml 中,您需要定义服务及其依赖项。阅读Dependency Injection,它应该更有意义。

    另外,@JimL 是对的,你不应该注入整个容器来访问一项服务,只需注入一项服务(knp_snappy.pdf)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 2016-03-12
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      相关资源
      最近更新 更多