首页 > 解决方案 > 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);

标签: phpsymfonydoctrine-ormsymfony4event-listener

解决方案


尝试$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());
    }
}

推荐阅读