Doctrine Entity Listeners
Entity listeners are defined as PHP classes that listen to a single Doctrine event on a single entity class. For example, suppose that you want to prepare a specific entity whenever it is loaded from the database. To do so, define a listener for the postLoad
Doctrine event. See documentation.
This way, in your case, everytime you fetch a User entity from the database, the property will be initialized and ready to use everywhere in your code. Note that i do not recommand using this for heavy tasks because it will significantly reduce your app performance.
src/EventListener/UserListener.php
namespace AppEventListener;
use AppEntityUser;
use AppServiceFileDownloader;
use DoctrineORMEntityManagerInterface;
use DoctrinePersistenceEventLifecycleEventArgs;
class UserListener
{
private $entityManager;
private $fileDownloader;
public function __construct(EntityManagerInterface $entityManager, FileDownloader $fileDownloader)
{
$this->entityManager = $entityManager;
$this->fileDownloader = $fileDownloader;
}
public function postLoad(User $user, LifecycleEventArgs $event): void
{
$path = $user->getProfilePicturePath();
$url = $this->fileDownloader->generatePresignedUrl($path);
$user->setProfilePicturePresignedUrl($url);
}
}
config/services.yaml
services:
AppEventListenerUserListener:
tags:
- {
name: doctrine.orm.entity_listener,
entity: 'AppEntityUser',
event: "postLoad"
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…