cacheItemPool = $cacheItemPool; $this->notificationRepository = $notificationRepository; } public function addNotification(UserInterface $u): int { if (!$u instanceof User) { return 0; } return $this->countUnreadByUser($u); } public function countUnreadByUser(User $user): int { $key = self::generateCacheKeyUnreadNotificationByUser($user); $item = $this->cacheItemPool->getItem($key); if ($item->isHit()) { return $item->get(); } $unreads = $this->notificationRepository->countUnreadByUser($user); $item ->set($unreads) // keep in cache for 15 minutes ->expiresAfter(60 * 15); $this->cacheItemPool->save($item); return $unreads; } public static function generateCacheKeyUnreadNotificationByUser(User $user): string { return 'chill_main_notif_unread_by_' . $user->getId(); } public function onEditNotificationComment(NotificationComment $notificationComment, LifecycleEventArgs $eventArgs): void { $this->resetCacheForNotification($notificationComment->getNotification()); } public function onPreFlushNotification(Notification $notification, PreFlushEventArgs $eventArgs): void { $this->resetCacheForNotification($notification); } private function resetCacheForNotification(Notification $notification): void { $keys = []; if (null !== $notification->getSender()) { $keys[] = self::generateCacheKeyUnreadNotificationByUser($notification->getSender()); } foreach ($notification->getAddressees() as $addressee) { $keys[] = self::generateCacheKeyUnreadNotificationByUser($addressee); } $this->cacheItemPool->deleteItems($keys); } }