记录每个请求Symfony

时间:2017-03-26 07:47:38

标签: php symfony doctrine-orm

我有一个symfony应用程序,我想在数据库中记录ROLE_ADMIN的每个任务。我已尝试添加新捆绑包,但我不确定如何在AppKernel.php中加载该捆绑包。您可以提供的任何指导都非常有帮助。

1 个答案:

答案 0 :(得分:4)

我会在kernel.request事件上创建一个事件监听器,并检查请求是否来自ROLE_ADMIN的用户。

首先创建服务并注入security.authorization_checkerdoctrine.orm.entity_manager

admin_log_listener:
    class: AppBundle\EventListener\AdminLogListener
    arguments: [ "@security.authorization_checker", "@doctrine.orm.entity_manager" ]
    tags:
        - { name: kernel.event_listener, event: kernel.request }

然后创建事件监听器:

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Doctrine\ORM\EntityManager;

class AdminLogListener {

    protected $authChecker;
    protected $entityManager;

    public function __construct(AuthorizationChecker $authChecker, EntityManager $entityManager)
    {
        $this->authChecker = $authChecker;
        $this->entityManager = $entityManager;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if ($this->authChecker->isGranted('ROLE_ADMIN')) {
            // Use $this->entityManager to send query or call a repository function
            // Refer to http://www.doctrine-project.org/api/orm/2.5/class-Doctrine.ORM.EntityManager.html
        }
    }
}