簡體   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