Hi everyone,
I'm building a custom addon for XenForo 2.3.x and I'm trying to implement caching in my controller to reduce database queries on my homepage. I'd appreciate some guidance on the correct approach.
What I'm trying to do:
Cache the result of multiple finder queries (threads, statistics) so they don't hit the database on every page load.
My current approach:
Fetching from cache:
Saving to cache:
My questions:
Any help or pointers to the relevant source files would be greatly appreciated. Thanks!
I'm building a custom addon for XenForo 2.3.x and I'm trying to implement caching in my controller to reduce database queries on my homepage. I'd appreciate some guidance on the correct approach.
What I'm trying to do:
Cache the result of multiple finder queries (threads, statistics) so they don't hit the database on every page load.
My current approach:
Fetching from cache:
PHP:
$cache = $this->app()->cache();
$key = 'index_data_v1';
$cachedData = $cache ? $cache->fetch($key) : null;
if ($cachedData !== false && $cachedData !== null) {
return $this->view('MyAddon:Page\Index', 'my_template', $cachedData);
}
Saving to cache:
PHP:
$viewParams = [
'news' => $news, // XF Entity Collection
'announcements' => $announcements, // XF Entity Collection
'latestThreads' => $latestThreads, // XF Entity Collection
'statistics' => [
'threads' => $forumStats['threads'] ?? 0,
'messages' => $forumStats['messages'] ?? 0,
'users' => $forumStats['users'] ?? 0,
]
];
if ($cache) {
$cache->save($key, $viewParams, 300);
}
My questions:
- Can XF Entity Collections (returned by
->fetch()) be serialized and stored in cache reliably? Or does$cache->save()silently fail or store corrupted data when passed objects? - Is
$this->app()->cache()the correct way to access the cache layer in a controller, or should I be usingSimpleCacheinstead? - What is the recommended pattern for caching finder results in XF 2.3? Should I cache only the entity IDs and re-fetch on cache hit, or convert entities to plain arrays?
- Does
$cache->fetch()returnfalseornullon a cache miss? I want to make sure my check is correct.
Any help or pointers to the relevant source files would be greatly appreciated. Thanks!