简体   繁体   English

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

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

On each of my controllers, i need to run security enforcing function from constructor. 在我的每个控制器上,我需要从构造函数运行安全性强制执行功能。 Problem is that i cannot run doctrine entity manager in constructor to load user id from session, and call findby function from on my user entity. 问题是我无法在构造函数中运行原则实体管理器来从会话中加载用户ID,并无法从用户实体上调用findby函数。 Only way i found is to call this security enforcing function on each of my actions, which is not optimal - code not clean, and alot of function calls. 我发现的唯一方法是在我的每个操作上都调用此安全实施函数,这不是最佳选择-代码不干净,并且有很多函数调用。 I have searched and test many of user solutions from stackoverflow - many of them is copy paste of others not working code. 我已经从stackoverflow搜索并测试了许多用户解决方案-其中许多是其他无法正常工作的代码的复制粘贴。 My services.yml file: 我的services.yml文件:

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

My DefaultController class (its sample controller): 我的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();

    }
}

I always having doctrine errors whatever i not do with constructor. 无论我不使用构造函数如何,我总是会遇到教义错误。 Often error example, when im trying to access website 当我尝试访问网站时,经常出现错误示例

PS. PS。 I'm using Symfony 2.8.2, this code examples are not from actual app 我正在使用Symfony 2.8.2,此代码示例并非来自实际应用

please allow me to suggest a different approach. 请允许我提出另一种方法。 You're better using symfony event system :) 您最好使用symfony事件系统:)

You can set up listeners to be executed before and after any action of your controller. 您可以将侦听器设置为在控制器的任何操作之前和之后执行。

Just tag the events you want to subscribe to and dispatch them oa service you create for security purposes. 只需标记您要订阅的事件,然后将其分派到您出于安全目的而创建的服务中即可。

Checkout symfony documentation regarding this How to Set Up Before and After Filters 签出有关此如何在过滤器之前和之后设置的 symfony文档

Good luck! 祝好运! :) :)

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

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