Symfony - EventListener 中不同状态的多个参数

Symfony - multiple arguments for different status in 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());
    }
}