Skip to content

Allow TagAwareCacheInterface to get cached items by tag #61549

@nbpenn

Description

@nbpenn

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']]

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions