亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Symfony Controller 上調用“addFlash”方法后將 flash

在 Symfony Controller 上調用“addFlash”方法后將 flash

Go
萬千封印 2022-12-23 12:27:28
我有一個 Symfony 服務,用于向數據庫添加警報(DOM 中的引導警報),以允許管理員審核應用程序的使用情況,并且該服務還將警報保存在會話存儲中以顯示警報,直到用戶關閉每個警報。這是服務方法的代碼:public function addAlert(DateTimeInterface $eventDatetime, string $eventType, string $data, UserInterface $user, string $alertId): bool{    $success = false;    try {        //Build alert entity        $alert = new UserAlert();        $alert->setDatetimeUTC($eventDatetime);        $alert->setEventType($eventType);        $alert->setMessage($data);        $alert->setUser($user);        //Save in database        $this->entityManager->persist($alert);        $this->entityManager->flush();        //Save in session        $success = $this->saveAlertInSession($alertId, $eventType, $data);    } catch (Throwable $throwable) {        $this->logger->critical("Add User Alert Service: Ko. Details: {$throwable->getMessage()}.");    }    return $success;}private function saveAlertInSession(string $alertId, string $eventType, string $data): bool{    $alerts = [];    try {        //Check if any alert is stored to retrieve        if ($this->session->has('alerts')) {            $alerts = $this->session->get('alerts');        }        //Add new alert        $alerts[$alertId] = [            'type' => $eventType,            'data' => $data,        ];        //Save to session        $this->session->set('alerts', $alerts);        $success = true;    } catch (Throwable $throwable) {        $success = false;        $message = "Save Alert Session: Ko. Details: {$throwable->getMessage()}.";        $this->logger->critical($message);    }    return $success;}我的問題是 Symfony 是否有一個事件偵聽器來在每次我在控制器上編寫以下行時自動調用此服務方法:$this->addFlash('success', $message);$this->addFlash('error', $message);$this->addFlash('warning', $message);現在,在我向 Flash Bag 消息中添加一條消息后,我的控制器將執行以下指令:$this->alertsService->addAlert($datetimeUTCNow, $eventType, $message, $user, $alertId);你知道有什么事件偵聽器可以避免每次控制器調用 addFlash 方法時都寫這一行嗎?我正在使用 Symfony 5 和 PHP 7.3
查看完整描述

1 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

這是我覆蓋 addFlash 方法的解決方案:


protected function addFlash(string $type, string $message): void

{

    // Generate the required arguments on userAlerts service

    try {

        $datetimeUTC = new DateTime('now', new DateTimeZone('UTC'));

        $alertId = Uuid::uuid4();


        $this->userAlertsService->addAlert($datetimeUTC, $type, $message, $this->getUser(), $alertId);

    } catch (Throwable $throwable) {

        $this->logger->critical("Add Flash: Ko. Details: {$throwable->getMessage()}");

    }


    parent::addFlash($type, $message);

}


查看完整回答
反對 回復 2022-12-23
  • 1 回答
  • 0 關注
  • 81 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號