1

我正在尝试创建一个自定义独白处理器以将当前用户附加到错误邮件。

像这样声明服务时:

monolog.processor.mail:
        class: MyVendor\Monolog\Processor\MailProcessor
        arguments:
            - @mailer
            - @security.context
        tags:
            - { name: monolog.processor, method: processRecord }

我得到一个循环引用:

[Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException]
Circular reference detected for service "monolog.processor.mail",
path: "router -> monolog.logger.router -> monolog.processor.mail
-> security.context -> security.authentication.manager
-> fos_user.user_provider.username_email-> fos_user.user_manager
-> doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection
-> doctrine.dbal.logger -> monolog.logger.doctrine".

这里的最佳实践解决方案是什么?

相关论坛主题: http: //forum.symfony-project.org/viewtopic.php?t=40306 &p=131081#p131143

该线程表明:

  • Setter 注入并不能解决问题(我也试过了)
  • 注入容器会导致不定式递归(我尚未确认)

还尝试了这个脚本http://pastebin.com/AuvFgTY3从会话中获取用户。

if ($this->session !== null) {
    if ($this->session->has($this->securityKey)) {
        $token = unserialize($this->session->get($this->securityKey));
        $this->currentUser = $token->getUser();
    }
}

这给出了以下错误:

Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in
C:\inetpub\symfony23\vendor\symfony\symfony\src\Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler.php
on line 56

我确实了解 security.context 尚未为很早就请求记录器的服务构建。对于我的班级来说,这不是问题,因为我会将用户设置为undefined. 所以理想情况下,security.context在服务创建后将被注入security.context。但是,我不能更改要构建的记录器的优先级,因为它是早期需要的。所以也许问题可以解决:如何在 security.context 初始化后重新创建服务?不确定范围原型在这里是否有帮助?

4

1 回答 1

4

根据内核请求创建处理程序并提取用户:

// src/AppBundle/Monolog/UserProcessor.php

namespace AppBundle\Monolog;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class UserProcessor
{
    private $tokenStorage;
    private $user;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function __invoke(array $record)
    {
        if (null !== $this->user) {
            $record['extra']['user'] = $this->user->getUsername();
        }

        return $record;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (null === $token = $this->tokenStorage->getToken()) {
            return;
        }

        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }

        $this->user = $user;
    }
}

注册新处理器:

# app/config/services.yml

services:
    monolog.processor.user:
    class: AppBundle\Monolog\UserProcessor
    arguments:  ["@security.token_storage"]
    tags:
        - { name: monolog.processor }
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Symfony 文档有问题

于 2015-09-09T07:58:58.587 回答