Caching
Cache
Concrete CMS uses cache to store data for quicker future retrieval.
Object Caching
Concrete uses a PSR-6 compatible caching layer with three default pools:
- cache: The primary, ephemeral cache, typically in-memory or using a fast caching driver. It's configurable via
concrete.cache.levels.object
. - cache/request: An ephemeral, single-request cache, replacing the CacheLocal API.
- cache/expensive: For performance-benefiting, slow cache items, generally on disk. It's loaded into ephemeral cache on access for faster subsequent use within the same request. Its drivers are configurable via
concrete.cache.levels.expensive
.
Basic API – Retrieving and Setting Items
Using the Object Cache
Example: Retrieving a "StudentList" object:
public static function getByCourseID($id)
{
$expensiveCache = \Core::make('cache/expensive');
$studentCourseList = $expensiveCache->getItem('StudentList/Course' . $id);
if ($studentCourseList->isMiss()) {
$studentCourseList->lock();
$list = StudentList::findBy(array('course_id' => $id));
$expensiveCache->save($studentCourseList->set($list)->expiresAfter(300)); // expire after 300 seconds
} else {
$list = $studentCourseList->get();
}
return $list;
}
This code caches 'StudentList/Course{$id}' in the expensive cache, fetching from the database if not found and adding it to the cache.
Notes
- Deeply nested cache items can create extensive directory structures.
- Be cautious of file path length limits on certain file systems.
Handling the Blackhole Cache
To avoid issues when the cache is disabled (using a 'BlackHole' cache), ensure $value
always contains the desired data:
$expensiveCache = \Core::make('cache/expensive');
$cacheObject = $expensiveCache->getItem('Cache/MyObject');
if ($cacheObject->isMiss()) {
$value = $this->lookupSomeValue();
$expensiveCache->save($cacheObject->set($value));
} else {
$value = $cacheObject->get();
}
echo $value;
Clearing the Cache
To invalidate a cache, for example, when a new student joins a course:
public addStudentToCourse($studentId, $courseId)
{
// Add student to the course code
$expensiveCache = \Core::make('cache/expensive');
$studentCourseList = $expensiveCache->getItem('StudentList/Course' . $courseId);
$studentCourseList->clear();
}
Cache invalidation also occurs when a user clears the cache via the dashboard.