Today, I’ll show you the Symfony Cache component, an easy way to add caching to your PHP applications. This helps improve the overall performance of your application by reducing the page load time.
The Symfony Cache Component
The Symfony Cache component allows you to set up caching in your PHP applications. The component itself is very easy to install and configure and allows you to get started quickly. Also, it provides a variety of adapters to choose from, as shown in the following list:
- database adapter
- filesystem adapter
- memcached adapter
- Redis adapter
- APCu adapter
- and more
When it comes to caching using the Symfony Cache component, there are a couple of terms that you should get familiar with.
The Symfony Cache component allows you to choose from the two different caching approaches.
PSR-6 Caching
It’s a generic cache system which revolves around cache pools and cache items.
To start with, the cache item refers to the content which is stored. Each item is stored as a key-value pair. Cache items are managed by the cache pool, which groups them logically. In fact, you need to use the cache pool to manipulate cache values.
Finally, it’s the cache adapter which does all the heavy lifting to store items in the cache back-end.
Cache Contracts
It’s a simple but more powerful way to cache values based on recomputation callbacks. It also comes with built-in Stampede prevention. It’s also the recommended way since it requires less code when it’s compared to the PSR-6 caching.
In this article, we’ll explore both ways to understand how you can unleash the power of the Symfony Cache component. As usual, we’ll start with installation and configuration, and then we’ll go on to explore a few real-world examples in the latter half of the article.
Installation and Configuration
In this section, we’re going to install the Cache component. I assume that you have already installed Composer in your system—you’ll need it to install the Cache component available at Packagist.
Once you have installed Composer, go ahead and install the Cache component using the following command.
$composer require symfony/cache
That should have created a composer.json file which should look like this:
"require": "symfony/cache": "^4.1"
That’s it for installation, but how are you supposed to add it to your application? It’s just a matter of including the autoload.php file created by Composer in your application, as shown in the following snippet.
<?php require_once './vendor/autoload.php'; // application code ?>
PSR-6 Caching: A Real-World Example
In this section, we’ll go through an example which demonstrates how you could use the Cache component in your applications to cache content with PSR-6 caching method.
To start with, let’s go ahead and create the index.php file with the following contents.
<?php require_once './vendor/autoload.php'; use Symfony\Component\Cache\Adapter\FilesystemAdapter; $cachePool = new FilesystemAdapter(); // 1. store string values $demoString = $cachePool->getItem('demo_string'); if (!$demoString->isHit()) $demoString->set('Hello World!'); $cachePool->save($demoString); if ($cachePool->hasItem('demo_string')) $demoString = $cachePool->getItem('demo_string'); echo $demoString->get(); echo "<br>"; // delete all items $cachePool->clear(); if (!$cachePool->hasItem('demo_string')) echo "The cache entry demo_string was deleted successfully!\n"; // 2. store array values $demoOne = $cachePool->getItem('demo_array'); if (!$demoOne->isHit()) $demoOne->set(array("one", "two", "three")); $cachePool->save($demoOne); if ($cachePool->hasItem('demo_array')) $demoOne = $cachePool->getItem('demo_array'); var_dump($demoOne->get()); echo "<br>"; // delete specific item $cachePool->deleteItem('demo_array'); if (!$cachePool->hasItem('demo_array')) echo "The cache entry demo_array was deleted successfully!\n"; echo "<br>"; // 3. set expiry on items $foo = $cachePool->getItem('foo'); if (!$foo->isHit()) $foo->set('bar'); $foo->expiresAfter(5); $cachePool->save($foo); if ($cachePool->hasItem('foo')) $foo = $cachePool->getItem('foo'); echo $foo->get(); echo "<br>"; sleep(6); if ($cachePool->hasItem('foo')) $foo = $cachePool->getItem('foo'); echo $foo->get(); echo "<br>"; else echo "Cache item was expired!\n";
Let’s go through the main parts of the index.php file to understand their purpose.
Create the Cache Pool
As we discussed earlier, cached items are stored in a cache pool. Furthermore, each cache pool is backed by a specific cache back-end and adapter. If you want to store items in the file system cache, for example, you need to initialize the cache pool of the file system adapter.
$cachePool = new FilesystemAdapter();
You can provide three optional arguments to the FilesystemAdapter
object:
- the namespace in which you would like to create cache entries
- a lifetime in seconds for cache items
- the directory in which the cache will be stored.
How to Store String Values
Since we’ve already created the cache pool, we can use it to store cache items.
Firstly, we’ve used the getItem
method to fetch the cache item with the demo_string
key. Next, we’ve used the isHit
method to check if the value we’re looking for is already present in the cache item $demoString
.
$demoString = $cachePool->getItem('demo_string'); if (!$demoString->isHit()) $demoString->set('Hello World!'); $cachePool->save($demoString);
Since this is the first time we’re fetching the demo_string
cache item, the isHit
method should return false
. Next, we’ve used the set
method of the $demoString
object to set the cache value. Finally, we’ve saved the $demoString
cache item into the $cachePool
cache pool using the save
method.
Now that we’ve stored the item in the cache, let’s see how to fetch it from the cache.
if ($cachePool->hasItem('demo_string')) $demoString = $cachePool->getItem('demo_string'); echo $demoString->get(); echo "\n";
Here, we’ve used the hasItem
method to check the existence of the cache item in the cache pool before retrieving it.
Next, let’s see how to delete all cache items from the cache pool:
$cachePool->clear();
How to Store Array Values
In the previous section, we discussed how to store basic values in the cache pool. Storing array values is pretty much the same, as you can see in the following example.
$demoOne = $cachePool->getItem('demo_array'); if (!$demoOne->isHit()) $demoOne->set(array("one", "two", "three")); $cachePool->save($demoOne); if ($cachePool->hasItem('demo_array')) $demoOne = $cachePool->getItem('demo_array'); var_dump($demoOne->get()); echo "\n";
As you can see, we can simply set the cache item with an array value, just the same as we did for a string.
Next, let’s see how to delete the specific cache item from the cache pool.
$cachePool->deleteItem('demo_array');
Here, we’ve used the deleteItem
method to delete the demo_array
item from the cache pool.
How to Set an Expiry Date for Cached Items
So far, we’ve cached items into the pool without an expiry date. However, you don’t typically want to store items in the cache permanently. For example, you want to refresh cache items periodically, so you need a mechanism which purges expired cache items.
In this section, we’ll discuss how to store items in the cache along with an expiry date.
$foo = $cachePool->getItem('foo'); if (!$foo->isHit()) $foo->set('bar'); $foo->expiresAfter(30); $cachePool->save($foo);
As you can see in the above snippet, you can use the expiresAfter
method to set an expiry date for the cached item. You can pass the number of seconds you would like to cache an item for in the first argument of the expiresAfter
method.
In our example, we’ve used the sleep
method to test if the cached item is still available in the cache pool.
if ($cachePool->hasItem('foo')) $foo = $cachePool->getItem('foo'); echo $foo->get(); echo "\n"; sleep(60); if ($cachePool->hasItem('foo')) $foo = $cachePool->getItem('foo'); echo $foo->get(); echo "\n"; else echo "Cache item was expired!\n";
Go ahead and test it to see how it works!
Cache Contracts: A Real-World Example
In this section, we’ll go through an example which demonstrates how you could use the Cache component in your applications to cache content with the help of Cache Contracts.
To start with, let’s go ahead and create the cache_contracts.php file with the following contents.
<?php require_once './vendor/autoload.php'; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Contracts\Cache\ItemInterface; $cachePool = new FilesystemAdapter(); // 1. store string values $value = $cachePool->get('demo_string', function (ItemInterface $item) return 'Hello World!'; ); echo $value; echo "<br>"; // delete specific item $cachePool->delete('demo_string'); // 2. set expiry on items $value = $cachePool->get('foo', function (ItemInterface $item) $item->expiresAfter(5); // retrieve/calculate the value of this cache item as you want $cacheItemValue="bar"; return $cacheItemValue; );
Let’s go through the main parts of the cache_contracts.php file to understand their purpose.
How to Store Cache Values With Cache Contracts
First of all, it’s important to note that Cache Contracts only support two methods. The get
method is used to get and set cache values. On the other hand, the delete
method is used to delete the cache item.
Now, let’s quickly look at the following snippet which is used to set and get the cache value at the same time.
$cachePool = new FilesystemAdapter(); $value = $cachePool->get('demo_string', function (ItemInterface $item) return 'Hello World!'; );
First of all, you need to initialize the cache pool instance. Now, we can use this object to set cache values with the help of Cache Contracts. As you can see, the first argument is a cache key and the second argument is a PHP callable which is only executed if the key is not found in the cache pool. The PHP callable is responsible for generating the cache value and returning it as well.
How to Set an Expiry Date for Cached Items With Cache Contracts
It’s very easy to set the cache item along with an expiry date. Let’s quickly look at the following snippet.
$value = $cachePool->get('foo', function (ItemInterface $item) $item->expiresAfter(5); // retrieve/calculate the value of this cache item as you want $cacheItemValue="bar"; return $cacheItemValue; );
As you can see, we’ve used the expiresAfter
method of the $item
object to set the expiration date.
Invalidate Cache Items With Cache Tags
When you create cache items, you can attach a tag with them. So it’s like keeping logically grouped cache items together under the same tag. It’s really useful when you want to delete all cache items that are related to each other, and don’t want to delete them by keys.
Let’s quickly look at the following snippet.
<?php require_once './vendor/autoload.php'; use Symfony\Component\Cache\Adapter\FilesystemTagAwareAdapter; use Symfony\Contracts\Cache\ItemInterface; $cachePool = new FilesystemTagAwareAdapter(); $value = $cachePool->get('foo_product_details', function (ItemInterface $item) $item->tag('foo'); return 'Hello World!'; ); $value = $cachePool->get('foo_product_categories', function (ItemInterface $item) $item->tag('foo'); return array('Category One', 'Category Two'); ); $value = $cachePool->get('foo_product_variations', function (ItemInterface $item) $item->tag('foo'); return array('Product Variation One', 'Product Variation Two'); ); $cachePool->invalidateTags(['foo']);
It’s important to note that when you want to attach tags to cache items, you need to use the tag aware cache adapter. Thus, we’ve used the FilesystemTagAwareAdapter
adapter which is the tag aware version of the FilesystemAdapter
adapter.
Next, you need to use the tag
method to attach a tag to the cache item. And finally, you can use the invalidateTags
method of the adapter class to remove cache entries associated with specific cache tags.
So that’s how you can use Cache Contracts for cache management in your projects.
Conclusion
Today, we had a brief look at the Symfony Cache component, which allows you to set up caching in your PHP applications. It also supports a variety of caching adapters that together give you the flexibility to choose the kind of back-end you want to use.