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

标签 php doctrine-orm symfony

我设置了一个监听器类,我将在其中设置任何 doctrine prePersist 的 ownerid 列。我的 services.yml 文件看起来像这样......

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

我的类(class)看起来像这样......

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();

}
}

此操作的结果是以下错误。

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".

我的假设是安全上下文已经被注入(inject)到链中的某处,但我不知道如何访问它。有任何想法吗?

最佳答案

我遇到了类似的问题,唯一的解决方法是在构造函数中传递整个容器(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');

        // ...
    }
}

关于php - 在 Symfony2 中将 SecurityContext 注入(inject)监听器 prePersist 或 preUpdate 以获取 createdBy 或 updatedBy 中的用户导致循环引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7561013/

相关文章:

php - Doctrine DQL 无效参数编号 : number of bound variables does not match number of tokens

symfony - 教义实体……历史?

forms - Bootstrap 3 : formatted checkboxes with Symfony & Twig

php - Symfony 2.5.3 和 PHP 5.6.0 : incompatibility issues?

php - 按行号选择值

php - 文本区域中最多允许 2 个换行符

PHP:以 OOP 方式搜索 CSV 文件

Symfony2 - 设置相关类别以动态发布

php - 在 PHP 中动态填充关联数组

php - 如何正确获取 Symfony 3 中的 EntityManager?