Symfony 2:在控制器之外获取安全上下文 [英] Symfony 2: Get Security Context Outside of Controller

查看:28
本文介绍了Symfony 2:在控制器之外获取安全上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个需要访问用户权限级别的事件侦听器.在控制器中我使用以下代码

I am trying to write an event listener that needs access to the users permission level. In the controller I use the following code

代码:

$securityContext = $this->container->get('security.context');

if($securityContext->isGranted('ROLE_USER')){
    //Do Something
}

但是在控制器之外,我不知道如何获取安全上下文.是否可以?

But outside of a controller I can't work out how to get the security context. Is it possible?

推荐答案

最好的方法是使用(如 phpisuber 所说)依赖注入通过服务容器.但是,与其注入整个容器(这被认为是不好的做法,因为它会使整个类的可测试性降低并打破松散耦合),您应该像这样注入 security.context 服务:

The best way to do this is using (as phpisuber said) dependency injection through the Service Container. But, instead of injecting the entire container (which is considered bad practice as it makes your entire class less testable and breaks loose coupling) you should inject the security.context service like so:

acme_foo.bar_service:
    class: %acme_foo.bar_service.class%
    arguments:
        - @security.context

您的服务可以是这样的:

Your service can be something like this:

<?php
namespace Acme\FooBundle\Service;

use Symfony\Component\Security\Core\SecurityContext;

class BarService
{
    /**
     * @var SecurityContext
     */
    protected $context;

    /**
     * @param SecurityContext $context
     */
    public function __construct($context)
    {
        $this->context = $context;
    }

    public function doSomething()
    {
        return $this->context->isGranted('ROLE_USER');
    }
}

这篇关于Symfony 2:在控制器之外获取安全上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆