Symfony 2.7:在null上调用成员函数get()

时间:2018-07-12 09:37:10

标签: php symfony controller

在Symfony 2.7应用程序中,我具有以下控制器:

namespace MyCompany\AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class PdfPrevewController extends Controller
{

    public function __construct()
    {
        //TODO: Inject the em instead of extending controller.
        //      (An error resulted when attempting to do that.)

        $this->em = $this->get('doctrine.orm.default_entity_manager');
    }

    /**
     * @Route("/admin/pdf-preview/by-document-id/{id}", name="pdf_preview_by_document_id")
     */
    public function createPdfPreviewAction($id = 0)
    {
        die('Started.');
    }
}

当我在浏览器中打开控制器时,收到以下消息:

  

错误:在null上调用成员函数get()

...我不太了解,因为扩展控制器类通常可以访问容器。我在这里想念什么?

====

更新:我还尝试将控制器定义为服务并在其中设置容器:

  app.controller.pdf_preview:
    class: Exozet\AppBundle\Controller\PdfPreviewController
    calls:
      - [setContainer, ['@service_container']]

...没有运气。仍然显示相同的错误消息。

1 个答案:

答案 0 :(得分:3)

    $this->em = $this->get('doctrine.orm.default_entity_manager');

在构造函数中尚不可用...而是使用依赖注入来设置您的entitymanager(干净方法)

public function __construct(EntityManagerInterface $entityManager)

{

    $this->em = $entityManager;
}

或稍后在另一个函数中调用该服务(当所有服务都已设置时)