【问题标题】:getDoctrine() null on Symfony 3.4Symfony 3.4 上的 getDoctrine() null
【发布时间】:2021-12-10 18:41:18
【问题描述】:

我在 symfony 3.4 项目中遇到错误。 我正在尝试在我的应用程序菜单中管理通知的显示。 所以我创建了一个扩展 Controller 的 CustomController。

然后我让所有其他控制器都继承自 CustomController。

但是当我调用 getDoctrine() 以访问存储库时,我收到以下错误:

"调用一个成员函数 has() on null"

这是我的自定义控制器:


<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;


class CustomController extends Controller
{
    public $data = [];
    protected $em;


    public function __construct()
    {
        $this->em = $this->getDoctrine()->getManager();
        $countAttente = $this->em->getRepository('AppBundle:Commandes')->tailleEnAttente("En attente");
        
        $this->data['countAttente'] = $countAttente;
    }
}

我尝试在 service.yml 中将控制器作为服务传递,但它没有改变任何东西

AppBundle\Controller\CustomController:
        class: AppBundle\Controller\CustomController
        arguments: ["@doctrine.orm.entity_manager"]
        calls:
            - [setContainer, ["@service_container"]]

我发现了许多关于此类错误的类似主题,但没有一个允许我跳过此错误

欢迎任何帮助

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    直接在构造函数中自动装配 EntityManager:

    use Doctrine\ORM\EntityManagerInterface;
    
    private $em;
    
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
    

    或者,如果您需要特定的存储库,并且使用默认配置设置自动装配,您也可以对存储库执行相同操作:

    private $repository;
    
    public function __construct(CommandesRepository $repository)
    {
        $this->repository = $repository;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2018-09-09
      • 2021-12-26
      相关资源
      最近更新 更多