php - Symfony - EventListener 中不同状态的多个参数
问题描述
我正在使用 Symfony Doctrine Events 在实体状态更新后触发通知。
我希望它触发postUpdate()
现有实体。我已经定义了所选状态的常量,并希望在触发消息之前对其进行识别。
const TRIAL = 'trial';
const PAID = 'paid';
const DELETED = 'deleted';
public function postUpdate(LifecycleEventArgs $args)
{
$this->handle($args, self::TRIAL);
}
/**
* @param $args
* @param $action
*/
private function handle($args, $action)
{
/** @var EntityManagerInterface $entityManager */
$entityManager = $args->getEntityManager();
$uow = $entityManager->getUnitOfWork();
$entity = $args->getObject();
$changes = $uow->getEntityChangeSet($entity);
if ((!$entity instanceof User) || (!array_key_exists("status", $changes))) {
return;
}
$email = $entity->getEmail();
$status = $entity->getStatus();
$msg = null;
if ($action == self::TRIAL) {
$msg = "{$email} launched with status {$status}";
}
if ($action == self::PAID) {
$msg = "{$email} launched with status {$status}";
}
if ($action == self::DELETED) {
$msg = "{$email} launched with status {$status}";
}
try {
$this->msgService->pushToChannel($this->msgChannel, $msg);
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
}
侦听器方法可以接收更改的状态参数以显示正确的消息吗?我们可以有多个参数,以便 Symfony 可以区分使用哪个状态?
喜欢:
$this->handle($args, self::TRIAL);
$this->handle($args, self::PAID);
$this->handle($args, self::DELETED);
解决方案
尝试$changes
像那样检查 (未测试,但你会明白的):
const TRIAL = 'trial';
const PAID = 'paid';
const DELETED = 'deleted';
public function postUpdate(LifecycleEventArgs $args)
{
$this->handle($args);
}
/**
* @param $args
*/
private function handle($args)
{
/** @var EntityManagerInterface $entityManager */
$entityManager = $args->getEntityManager();
$uow = $entityManager->getUnitOfWork();
$entity = $args->getObject();
$changes = $uow->getEntityChangeSet($entity);
if ((!$entity instanceof User) || (!array_key_exists("status", $changes))) {
return;
}
$email = $entity->getEmail();
$msg = null;
// Check if the status has changed
if(!empty($changes["status"])){
// $changes["status"] contain the previous and the new value in an array like that ['previous', 'new']
// So whe check if the new value is one of your statuses
if(in_array($changes["status"][1], [self::TRIAL, self::PAID, self::DELETED])) {
$msg = "{$email} launched with status {$status}";
}
}
try {
$this->msgService->pushToChannel($this->msgChannel, $msg);
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
}
推荐阅读
- c - netstat 和 program 中的不同端口
- javascript - 如何解决“找不到此相关模块:”问题?(Vue)
- reactjs - 多次调用使用效果
- javascript - 如何在 JavaScript 中顺序组合两个同步迭代器?
- python - 使用 Python 将 Atom 或 OData XML 文件转换为 OData Json 文件
- c - 是否可以仅在 C 中的一定时间后执行条件
- c++ - 如何将 GLFW 库链接到 CLION (Windows)?
- reactjs - 使用 React 中的 Fetch api 从 createContext 中的 api 获取数据不起作用
- javascript - 是否可以@link 到 useEffect
- masstransit - MassTransing SQS/SNS - 如何在所有主题上启用静态加密