Symfony 2.8:无法在自定义中使用容器 class

Symfony 2.8: Can't manage to use container in custom class

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

Error: Call to a member function get() on a non-object

代码如下:

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

你们知道问题出在哪里吗?

感谢您的帮助。

您的 class 不能 "see" 任何服务(包括容器),除非您 "inject" 它。在 YourCustomBundle/Resources/config/services.xml 中,您需要定义服务及其依赖项。继续阅读 Dependency Injection,它应该更有意义。

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

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

请看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

希望对您有所帮助!