я начал работать над новым проектом Симфония 6.0.
Я создал новую сущность под названием Project
. В этом объекте я хочу автоматически установить свойство created_by
при вызове PrePersist
(ловушка)...
Поэтому я создал AbstractEntity
, чтобы расширить исходную Project
сущность.
В AbstractEntity
я хочу автоматически внедрять Symfony\Component\Security\Core\Security
сервис.
НО материал autowire просто не работает.
# 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;
}
}
🤔 А знаете ли вы, что...
PHP обеспечивает безопасность с помощью механизмов фильтрации ввода.
Сущность не должна иметь никаких зависимостей и содержать логику. Если вы хотите что-то сделать, рассмотрите возможность создания Слушатели жизненного цикла доктриныprePersist
или Слушатели сущностей Doctrine.
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
наш слушатель установит текущего пользователя.