繁体   English   中英

Symfony2传递给构造函数学说的实体管理器引发错误

[英]Symfony2 passing to constructor doctrine entity manager throwing error

在我的每个控制器上,我需要从构造函数运行安全性强制执行功能。 问题是我无法在构造函数中运行原则实体管理器来从会话中加载用户ID,并无法从用户实体上调用findby函数。 我发现的唯一方法是在我的每个操作上都调用此安全实施函数,这不是最佳选择-代码不干净,并且有很多函数调用。 我已经从stackoverflow搜索并测试了许多用户解决方案-其中许多是其他无法正常工作的代码的复制粘贴。 我的services.yml文件:

services:
    app.default_controller:
        class: AppBundle\Controller\DefaultController
        arguments:
            - @doctrine.orm.entity_manager

我的DefaultController类(其示例控制器):

<?php

namespace AppBundle\Controller;
use Doctrine\ORM\EntityManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    protected $em;
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', array(
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
        ));
    }

    public function __construct(EntityManager $em = null){
        $this->em=$em;

      $personRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle\Entity\Person');
        //$em = $this->getDoctrine()->getManager();

    }
}

无论我不使用构造函数如何,我总是会遇到教义错误。 当我尝试访问网站时,经常出现错误示例

PS。 我正在使用Symfony 2.8.2,此代码示例并非来自实际应用

请允许我提出另一种方法。 您最好使用symfony事件系统:)

您可以将侦听器设置为在控制器的任何操作之前和之后执行。

只需标记您要订阅的事件,然后将其分派到您出于安全目的而创建的服务中即可。

签出有关此如何在过滤器之前和之后设置的 symfony文档

祝好运! :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM