AbstractEntity 中的依赖注入

DependencyInjection in AbstractEntity

我开始研究一个新的 Symfony 6.0 项目。

我创建了一个名为 Project 的新实体。在这个实体中,我想在 PrePersist (挂钩)调用上自动设置 created_by 属性 ... 因此我创建了一个 AbstractEntity 来扩展原来的 Project 实体。

AbstractEntity我想自动注入Symfony\Component\Security\Core\Security服务。

但是自动装配的东西不起作用。

# config/services.yaml
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/' # --> i removed that line (doesnt work)
            - '../src/Kernel.php'

    #this also does not work
    App\Entity\AbstractEntity:
        autowire: true

    #this also does not work
    App\Entity\AbstractEntity:
        arguments:
            - '@security.helper'
// src/Entity/AbstractEntity.php
<?php 

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Security;

#[ORM\MappedSuperclass]
#[ORM\HasLifecycleCallbacks]
abstract class AbstractEntity
{
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }
}

实体不应有任何依赖关系并包含逻辑。如果你想做点什么,考虑创建 Doctrine Lifecycle Listeners prePersist or Doctrine Entity Listeners.


Lifecycle listeners are defined as PHP classes that listen to a single Doctrine event on all the application entities.


添加到 services.yaml 文件

App\EventListener\CreatedByLifecycleEvent:
    tags:
        -
            name: 'doctrine.event_listener'
            event: 'prePersist'

并创建一个监听器

namespace App\EventListener;
 
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Security;

class CreatedByLifecycleEvent
{
    private $security;
    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function prePersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if(method_exists($entity,'setCreatedBy') and !empty($user = $this->security->getUser())){
            $entity->setCreatedBy($user);
        }
    } 
}

因此,当保存任何实体时,只要存在 setCreatedBy 方法,我们的侦听器将设置当前用户。