DependencyInjection in AbstractEntity



我开始开发新的Symfony 6.0项目。

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

我想在AbstractEntity中自动注入SymfonyComponentSecurityCoreSecurity服务。

但是自动加载的东西就是不起作用。

# 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
AppEntityAbstractEntity:
autowire: true
#this also does not work
AppEntityAbstractEntity:
arguments:
- '@security.helper'
// src/Entity/AbstractEntity.php
<?php 
namespace AppEntity;
use DoctrineORMMapping as ORM;
use SymfonyComponentSecurityCoreSecurity;
#[ORMMappedSuperclass]
#[ORMHasLifecycleCallbacks]
abstract class AbstractEntity
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
}

实体不应该有任何依赖关系并包含逻辑。如果你想做点什么,考虑创建信条生命周期监听器prePersist或信条实体监听器。


生命周期侦听器被定义为侦听单个对象的PHP类所有应用程序实体上的Doctrine事件。


添加到服务。yaml文件

AppEventListenerCreatedByLifecycleEvent:
tags:
-
name: 'doctrine.event_listener'
event: 'prePersist'

创建一个监听器

namespace AppEventListener;

use DoctrinePersistenceEventLifecycleEventArgs;
use SymfonyComponentSecurityCoreSecurity;
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方法,我们的侦听器将设置当前用户。

相关内容

  • 没有找到相关文章

最新更新