-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Open
Description
Description
It seems like the only advantage to using a tag aware cache is for invalidation, it would be a nice feature to be able to load all cached objects by a tag.
Example
Something like:
class Course
{
protected string $teacherName;
protected string $subject;
public function getTeacherName(): string
{
return $this->teacherName;
}
public function getSubject(): string
{
return $this->subject;
}
public function setTeacherName(string $teacherName): static
{
$this->teacherName = $teacherName;
}
public function setSubject(string $subject): static
{
$this->subject = $subject;
}
}
class CourseService
{
public function __construct(
protected TagAwareCacheInterface $tagCache
) {}
public function getCoursesByTeacherName(string $teacherName): array
{
return $this->tagCache->getItemsByTag($teacherName);
}
public function getCoursesBySubject(string $subject): array
{
return $this->tagCache->getItemsByTag($subject);
}
}
$bobScience = new Course();
$bobScience->setTeacherName('bob')->setSubject('science');
$bobMath = new Course();
$bobMath->setTeacherName('bob')->setSubject('math');
$gailScience = new Course();
$gailScience->setTeacherName('gail')->setSubject('science');
$samMath = new Course();
$samMath->setTeacherName('sam')->setSubject('math');
foreach([$bobScience, $bobMath,$gailScience,$samMath] as $course){
$cacheKey = $course->getTeacherName() . '-' . $course->getSubject();
$this->tagCache->get($cacheKey, function(ItemInterface $item) use ($course) {
$item->tag([$course->getTeacher(), $course->getSubject()]);
return $course;
})
}
$courseService = new CourseService();
$mathCourses = $courseService->getCoursesBySubject('math');
// [Course('bob', 'math'), Course['sam','math']]
$bobCourses = $courseService->getCoursesByTeacherName('bob');
// [Course('bob', 'science'), Course['bob','math']]
$scienceCourses = $courseService->getCoursesBySubject('science');
// [Course('bob', 'science'), Course['gail','science']]