在我的每个控制器上,我需要从构造函数运行安全强制函数。问题是我无法在构造函数中运行原则实体管理器以从会话加载用户 ID,并从我的用户实体上调用 findby 函数。我发现的唯一方法是在我的每个操作上调用此安全强制函数,这不是最佳的 - 代码不干净,并且有很多函数调用。我已经从stackoverflow中搜索并测试了许多用户解决方案 - 其中许多是复制粘贴其他不起作用的代码。我的服务.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();
}
}
无论我不对构造函数做什么,我总是有教义错误。经常出错的例子,当im试图访问网站时
附言。我使用的是Symfony 2.8.2,此代码示例不是来自实际应用程序
请允许我提出一种不同的方法。你最好使用symfony事件系统:)
您可以将侦听器设置为在控制器的任何操作之前和之后执行。
只需标记要订阅的事件,并将其分派给您出于安全目的而创建的服务。
查看有关此的symfony文档 如何设置之前和之后的过滤器
祝你好运!:)