Symfony 3.4 Cache Example

Symfony has a very powerful built-in caching. You can use it directly by calling the default app cache and use it.

use Symfony\Component\Cache\Adapter\FilesystemAdapter;

//....

function getCachedData()
{

    /**
     * @var FilesystemAdapter $cache
     */
    $cache = $this->get('cache.app');

    //Define a key for the item
    $cacheKey = 'SOME_UNIQUE_KEY';

    //Fetch the cached item from the cache
    $cacheItem = $cache->getItem($cacheKey);

    //Check if the cache is present and is still valid.
    if ($cacheItem->isHit()) {
        //Get the cached value and return
        $data = $cache->getItem($cacheKey)->get();
        return $data;
    }

    //Since there is no cache available you can prepare the data
    $data = [10,20,30];

    //Set the data to cache object
    $cacheItem->set($data);

    //You can set an expire time if you need.
    //Below I have set the cache to 1 hour.
    $cacheItem->expiresAfter(60 * 60);

    //Save the cache
    $cache->save($cacheItem);

    //Return the data
    return $data;
}

//....

You can use this a lot in your application in places where you access databases or accessing the web services.

Have a great day 😊

By Imthiaz

Programmer, SAAS, CMS & CRM framework designer, Love Linux & Apple products, Currently addicted to mobile development & working @bluebeetle