php 将 SecurityContext 注入 Symfony2 中的侦听器 prePersist 或 preUpdate 以在 createdBy 或 updatedBy 中获取用户导致循环引用错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7561013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:57:06  来源:igfitidea点击:

Injecting SecurityContext into a Listener prePersist or preUpdate in Symfony2 to get User in a createdBy or updatedBy Causes Circular Reference Error

phpdoctrine-ormsymfony

提问by Jeremy

I setup a listener class where i'll set the ownerid column on any doctrine prePersist. My services.yml file looks like this ...

我设置了一个监听器类,在那里我将在任何学说 prePersist 上设置 ownerid 列。我的 services.yml 文件看起来像这样......

services:
my.listener:
    class: App\SharedBundle\Listener\EntityListener
    arguments: ["@security.context"]
    tags:
        - { name: doctrine.event_listener, event: prePersist }

and my class looks like this ...

我的班级看起来像这样......

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\SecurityContextInterface;

class EntityListener
{

protected $securityContext;

public function __construct(SecurityContextInterface $securityContext)
{
    $this->securityContext = $securityContext;
}


/**
 *
 * @param LifecycleEventArgs $args 
 */
public function prePersist(LifecycleEventArgs $args)
{

    $entity = $args->getEntity();
    $entityManager = $args->getEntityManager();

    $entity->setCreatedby();

}
}

The result of this is the following error.

这样做的结果是以下错误。

ServiceCircularReferenceException: Circular reference detected for service "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> my.listener -> security.context -> security.authentication.manager -> fos_user.user_manager".

ServiceCircularReferenceException:检测到服务“doctrine.orm.default_entity_manager”的循环引用,路径:“doctrine.orm.default_entity_manager -> Doctrine.dbal.default_connection -> my.listener -> security.context -> security.authentication.manager -> fos_user .user_manager”。

My assumption is that the security context has already been injected somewhere in the chain but I don't know how to access it. Any ideas?

我的假设是安全上下文已经注入链中的某个地方,但我不知道如何访问它。有任何想法吗?

回答by gilden

I had similar problems and the only workaround was to pass the whole container in the constructor (arguments: ['@service_container']).

我遇到了类似的问题,唯一的解决方法是在构造函数 ( arguments: ['@service_container']) 中传递整个容器。

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyListener
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    // ...

    public function prePersist(LifeCycleEventArgs $args)
    {
        $securityContext = $this->container->get('security.context');

        // ...
    }
}

回答by Anyone

As of Symfony 2.6 this issue should be fixed. A pull request has just been accepted into the master. Your problem is described in here. https://github.com/symfony/symfony/pull/11690

从 Symfony 2.6 开始,这个问题应该被修复。一个 pull request 刚刚被 master 接受。您的问题在此处描述。 https://github.com/symfony/symfony/pull/11690

As of Symfony 2.6, you can inject the security.token_storageinto your listener. This service will contain the token as used by the SecurityContextin <=2.5. In 3.0 this service will replace the SecurityContext::getToken()altogether. You can see a basic change list here: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service

从 Symfony 2.6 开始,您可以将 注入security.token_storage到您的侦听器中。此服务将包含SecurityContext<=2.5 中使用的令牌。在 3.0 中,此服务将SecurityContext::getToken()完全取代。您可以在此处查看基本更改列表:http: //symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service

Example usage in 2.6:

2.6 中的示例用法:

Your configuration:

您的配置:

services:
    my.entityListener:
        class: App\SharedBundle\Listener\EntityListener
        arguments:
            - "@security.token_storage"
        tags:
            - { name: doctrine.event_listener, event: prePersist }


Your Listener


你的听众

namespace App\SharedBundle\Listener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class EntityListener
{
    private $token_storage;

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

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entity->setCreatedBy($this->token_storage->getToken()->getUsername());
    }
}



For a nice created_by example, you can use https://github.com/hostnet/entity-blamable-component/blob/master/src/Listener/BlamableListener.phpfor inspiration. It uses the hostnet/entity-tracker-component which provides a special event that is fired when an entity is changed during your request. There's also a bundle to configure this in Symfony2

对于一个不错的 created_by 示例,您可以使用https://github.com/hostnet/entity-blamable-component/blob/master/src/Listener/BlamableListener.php获取灵感。它使用 hostnet/entity-tracker-component 提供一个特殊事件,当您的请求期间实体发生更改时会触发该事件。还有一个包可以在 Symfony2 中配置它

回答by Nikita Leshchev

There's a great answer already in this thread but everything changes. Now there're entity listeners classes in Doctrine: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners-class

这个线程中已经有一个很好的答案,但一切都变了。现在 Doctrine 中有实体侦听器类:http: //docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners-class

So you can add an annotation to your entity like:

因此,您可以向实体添加注释,例如:

/**
 * @ORM\EntityListeners({"App\Entity\Listener\PhotoListener"})
 * @ORM\Entity(repositoryClass="App\Repository\PhotoRepository")
 */
class Photo 
{
    // Entity code here...
}

And create a class like this:

并创建一个这样的类:

class PhotoListener
{        
    private $container;

    function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /** @ORM\PreRemove() */
    public function preRemoveHandler(Photo $photo, LifecycleEventArgs $event): void
    {
         // Some code here...
    }
}

Also you should define this listener in services.ymllike that:

你也应该services.yml像这样定义这个监听器:

photo_listener:
  class: App\Entity\Listener\PhotoListener
  public: false
  autowire: true
  tags:
    - {name: doctrine.orm.entity_listener}

回答by Calin Bolea

I use the doctrine config files to set preUpdateor prePersistmethods:

我使用教义配置文件来设置preUpdateprePersist方法:

Project\MainBundle\Entity\YourEntity:
    type: entity
    table: yourentities
    repositoryClass: Project\MainBundle\Repository\YourEntitytRepository
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO

    lifecycleCallbacks:
        prePersist: [methodNameHere]
        preUpdate: [anotherMethodHere]

And the methods are declared in the entity, this way you don't need a listener and if you need a more general method you can make a BaseEntity to keep that method and extend the other entites from that. Hope it helps!

并且方法在实体中声明,这样您就不需要侦听器,如果您需要更通用的方法,您可以创建一个 BaseEntity 来保留该方法并从中扩展其他实体。希望能帮助到你!