Caching in PHP Web Applications: A Developer Guide
Caching improves the performance and scalability of web applications by reducing the server load and database queries
Caching is a technique that improves the performance and scalability of web applications by storing frequently used data in memory, so that it can be retrieved faster and with less server load. Caching can also reduce the bandwidth consumption and latency of web applications by serving cached content to the clients instead of fetching it from the original source.
Different types of caching that can be applied to different layers of a web application. These caching types include:
- Client-side caching: This involves storing data and content on the browser or user device, so that it can be accessed without sending requests to the server. Client-side caching is implemented using HTTP headers, such as
Cache-Control
,Expires
,ETag
andLast-Modified.
These headers instruct the browser how to cache and validate the content. Client-side caching can also be implemented using JavaScript APIs likelocalStorage
,sessionStorage
andIndexedDB
, which allow storing data on the browser’s storage. - Server-side caching: This caching technique involves storing data on the web server or a dedicated cache server, so that it can be accessed faster and with less database queries or external API calls. Server-side caching can be implemented using PHP extensions, such as
APCu
,Memcached
andRedis.
These extensions provide in-memory key-value stores that can store and retrieve data quickly. PHP frameworks, such asLaravel
,Symfony
andCodeIgniter
also provide built-in caching features and integrations with cache servers, thus can be used to implement server-side caching. - Reverse proxy caching: This involves storing data on an intermediate server, such as
Nginx
orVarnish
, which sits between the web server and the clients. These servers are intermediators and acts as a proxy that intercepts and caches the requests and responses. Reverse proxy caching can improve the performance and scalability of web applications. It achieves this by reducing the load on the web server and serving cached content to multiple clients. Reverse proxy caching can also provide additional features, such as compression, encryption, load balancing and security.
Server-side caching is especially important for dynamic web applications that rely on database queries and external API calls to generate content. It can avoid repeated and unnecessary computations and improve the responsiveness of PHP web applications. Server-side caching can also be useful for static web applications that serve large and frequently accessed files, such as images, videos, or scripts. Therefore, caching these files on the server reduces the network latency and bandwidth consumption
Various PHP and standalone extensions likeAPCu
, Memcached
and Redis
are used in implementing caching in PHP web applications. Assuming that you have installed these extensions on your web server, let’s dive into how they can be used to implement server-side caching in PHP.
APCu
APCu (APC User Cache) is a PHP extension that provides an in-memory key-value store that can store and retrieve data quickly. It is a successor of APC (Alternative PHP Cache), which also provided opcode caching for PHP scripts. However, since PHP 7 introduced its own opcode cache (OPcache), APCu only provides user cache functionality.
To use APCu, you need to enable it in your php.ini file by setting apc.enabled=1
. You also need to set the amount of memory allocated for APCu by setting apc.shm_size
. For example, to allocate 128 MB of memory for APCu, you can set apc.shm_size=128M
.
The function apcu_store($key, $value, $ttl)
is used to store data in APCu. In this function, $key
is a unique identifier for the data, $value
is the data to be stored, and $ttl
is an optional parameter that specifies the time to live (in seconds) for the data. For example, to store an array of products in APCu with a key of “products” and a time to live of one hour, you can use:
$products = [
["id" => 1, "name" => "Salt", "price" => 10],
["id" => 2, "name" => "Sugar", "price" => 20],
["id" => 3, "name" => "Cheese", "price" => 30],
];
apcu_store("products", $products, 3600);
The function apcu_fetch($key)
is used to retrieve data from APCu, where $key
is the identifier for the data. Fetching the array of products from APCu with a key of “products” can be implemented as shown in the code block below:
$products = apcu_fetch("products");
Deleting data from APCu is achieved using the function apcu_delete($key)
, where $key
is the identifier for the data. However, to clear all the data from APCu, the function apcu_clear_cache()
applies. For instance, the code block shows how to deletes the array of products from APCu with a key of “products” and how to clear the data from the APCu.
apcu_delete("products"); #deleting specified data using an identifier
apcu_clear_cache(); #clearing all the data
To check if a key exists in APCu, you can use the function apcu_exists($key)
, where $key
is the identifier for the data. For example, to check if the key “products” exists in APCu, the following code applies:
if (apcu_exists("products")) {
echo "The key 'products' exists in APCu.";
} else {
echo "The key 'products' does not exist in APCu.";
}
Memcached
Memcached is a caching system that can be used to achieve server-side caching in PHP web applications. It is a distributed in-memory key-value store that can store and retrieve data quickly. Although Memcached is not a PHP extension, it has proven handy in achieving caching in dynamic applications built using PHP. It is a standalone server that can be accessed by multiple clients using different programming languages. To use Memcached with PHP, you need to install and configure the Memcached server on your web server, and also install the PHP extension memcached
on your web server.
Using Memcached requires one to create an instance of the class Memcached
and add one or more servers to it using the method addServer($host, $port, $weight).
In this case,$host
is the hostname or IP address of the Memcached server, $port
is the port number of the Memcached server, and $weight
is an optional parameter that specifies the relative probability of using this server. For example, creating an instance of Memcached and adding a local server with a default port of 11211 and a weight of 1 can be achieved with the code below:
$memcached = new Memcached();
$memcached->addServer("localhost", 11211, 1);
The method set($key, $value, $expiration)
is used to store data in Memcached. As already seen,$key
is a unique identifier for the data, $value
is the data to be stored, and $expiration
is an optional parameter that specifies the expiration time (in seconds) for the data. The code block below stores an array of products in Memcached with a key of “products” and an expiration time of one hour.
$products = [
["id" => 1, "name" => "Salt", "price" => 10],
["id" => 2, "name" => "Magarine", "price" => 20],
["id" => 3, "name" => "Sugar", "price" => 30],
];
$memcached->set("products", $products, 3600);
To retrieve data from Memcached, the method get($key)
, where $key
is the identifier for the data is used. Retrieval of data can be achieved as shown below:
$products = $memcached->get("products");
The method delete($key)
is used to delete data from Memcached, while flush()
is used to clear all the data from Memcached. The delete method has $key
as the identifier for the data. Deleting and clearing data from me Memcached can be achieved using the following lines of code, respectively:
$memcached->delete("products");#deleting specified data using an identifier
$memcached->flush(); #clearing all the data
On the other hand, theget($key)
method is used to check if a key exists in Memcached and check if it returns a false. This can be implemented using the code below:
if ($memcached->get("products") !== false) {
echo "The key 'products' exists in Memcached.";
} else {
echo "The key 'products' does not exist in Memcached.";
}
The code above checks of the key “products” exists in Memcached.
Redis
Redis is another powerful NoSQL data store used to achieve server-side caching in PHP web apps. It is an in-memory data structure store that can store and retrieve data quickly. Redis is also not a PHP extension, but can be used with PHP when installed and configured on the web server. To use it, you also need to install the PHP extension redis
on your web server.
An instance of the class Redis
is created and connected to a server using the method connect($host, $port)
to use Redis. Let’s create an instance of Redis and connect to a local server with a default port of 6379.
$redis = new Redis();
$redis->connect("localhost", 6379);
The method set($key, $value)
is used to store data in Redis. In this case, $key
is a unique identifier for the data and $value
is the data to be stored. For instance, to store an array of products in Redis with a key of “products”, the code block below applies:
$products = [
["id" => 1, "name" => "Product A", "price" => 10],
["id" => 2, "name" => "Product B", "price" => 20],
["id" => 3, "name" => "Product C", "price" => 30],
];
$redis->set("products", serialize($products));
Note that Redis can only store strings as values, so you need to serialize the array before storing it.
To retrieve data from Redis, use the method get($key)
, where $key
is the identifier for the data. For instance, to fetch the array of products from Redis with a key of “products”, use the code:
$products = unserialize($redis->get("products"));
Since the array was serialized when storing, you need to unserialize the string before using it as an array as shown in the code above.
Delete data from Redis using specified identifier is achieved by the method del($key)
, while clearing all the data from Redis is done by the method flushAll()
. In PHP, deleting and clearing data from Redis is implemented as shown below:
$redis->del("products"); #deleting specified data using an identifier
$redis->flushAll(); #clearing all the data
Let’s Recap
In this guide, we have learned how to use server-side caching in PHP web applications using the APCu PHP extensions and other standalone extensions like Memcached and Redis. The article has shown how to store, retrieve, delete and check data using these extensions.
Server-side caching can improve the performance and scalability of web applications by reducing the server load and database queries. However, server-side caching also introduces some challenges, such as cache invalidation, cache consistency and cache security. Therefore, it is important to choose the right caching strategy and extension for your web application based on your requirements and preferences.
Until next time, nerds!
Find more of my work below: