Caching

PHPFast includes a powerful caching system that helps store and retrieve data efficiently. The framework provides a RedisCache class, offering essential methods like set(), get(), and delete() for interacting with a Redis server. This caching mechanism significantly improves performance, especially when handling data that doesn't change frequently.

Caching in Controllers

To enable caching in your controllers, use the RedisCache class or other (see more at Cache). Cache settings are configured in application/Config/Config.php

Here's how you can implement caching in HomeController. Simply uncomment the relevant caching lines to activate the functionality:

<?php

namespace App\Controllers;

use System\Core\BaseController;
use System\Libraries\Render;
use System\Drivers\Cache\RedisCache;

class HomeController extends BaseController
{
    protected $usersModel;
    protected $cache;

    public function __construct()
    {
        // Load cache configuration and initialize Redis cache
        $config = config('cache');
        $this->cache = new RedisCache($config);
    }


    public function index()
    {
        $cacheKey = 'home_page';

        // Check if cached content is available
        if ($cachedContent = $this->cache->get($cacheKey)) {
            echo $cachedContent;
            echo 'Loaded from cache.<br />';
            return;
        }

        // Generate the full page content
        $content = $this->render('themes', 'home/home');

        // Store the rendered page in cache for 10 minutes
        $this->cache->set($cacheKey, $content, 600);

        // Display the generated content
        echo $content;
    }
}

Configure Cache Settings

Modify application/Config/Config.php to enable caching:

Using Cache

Setup in Controller

Store and Retrieve Cached Data

Clear and Delete Cached Data

circle-info

Note

  • Best for Static Content – Use caching for data that doesn’t change often, like homepage content or user lists.

  • Set Expiration Time – Always define a cache expiration time to avoid showing outdated information.

  • Customize as Needed – Adjust caching settings based on your application’s needs for better performance and efficiency.

Last updated

Was this helpful?