
On this fast tip, we’ll discuss what caching is and the way we are able to use it in PHP.
It’s essential to give attention to efficiency when growing PHP apps. Net apps can have 1000's and even thousands and thousands of customers, which may result in sluggish efficiency and availability points. Caching is invaluable on this respect, as it will possibly assist keep away from efficiency pitfalls.
What's Caching?
Caching is a method to retailer ceaselessly accessed knowledge in a brief storage location to scale back the variety of occasions the information must be retrieved from its unique storage location. This may enormously enhance the efficiency of an internet site or software, as accessing knowledge from cache is mostly a lot quicker than accessing it from its supply.
PHP supplies a number of methods to implement caching. Let’s take a look at every of them.
Output Buffering
Output buffering is a way in PHP that permits us to retailer the output of a PHP script in a buffer, reasonably than sending it on to the browser. This permits us to switch the output or carry out different actions on it earlier than it’s exhibited to the person.
To start out an output buffer, we are able to use the ob_start()
perform. This perform will flip output buffering on and start capturing all output despatched by the script. The output can then be saved in a variable utilizing the ob_get_contents()
perform. Lastly, the output buffer could be ended and the output could be despatched to the browser utilizing the ob_end_flush()
perform, or it may be discarded utilizing the ob_end_clean()
perform.
Right here’s an instance of how output buffering works:
<?php
ob_start();
echo 'This output might be saved within the buffer';
$output = ob_get_contents();
ob_end_clean();
echo 'This output might be despatched to the browser';
On this explicit instance, the string 'This output might be despatched to the browser'
might be echoed solely as soon as, since we’re discarding the contents of the output buffer that comprises the primary echo instruction.
Output buffering can be utilized as cache, because it permits us to retailer the output of a PHP script in reminiscence, reasonably than producing it each time the script is accessed.
Caching Capabilities
PHP supplies a number of capabilities particularly for caching knowledge, together with apc_store()
, memcache_set()
, and xcache_set()
. These capabilities can be utilized to retailer knowledge in reminiscence, which could be accessed a lot quicker than knowledge saved on a tough drive.
apc_store()
The apc_store()
perform is a part of the Different PHP Cache (APC) extension, which supplies an opcode cache for PHP. (Opcode cache is a efficiency optimization method for PHP that caches the compiled bytecode of PHP scripts in reminiscence, reasonably than re-parsing and re-compiling the supply code on every request.) It shops a price within the APC cache with a specified key and expiration time.
Right here’s an instance of the way to use the apc_store()
perform to cache a price in reminiscence:
<?php
$worth = 'That is the worth to cache';
apc_store('cache_key', $worth, 3600);
To retrieve the cached worth, we are able to use the apc_fetch()
perform:
<?php
$cachedValue = apc_fetch('cache_key');
if ($cachedValue) {
echo $cachedValue;
} else {
$worth = 'That is the worth to cache';
apc_store('cache_key', $worth, 3600);
echo $worth;
}
Extra info on apc_store()
could be discovered right here.
memcache_set()
The memcache_set()
perform is a part of the Memcache extension, which lets you use a Memcache server as a cache for PHP. It shops a price within the Memcache server with a specified key and expiration time.
Extra info on memcache_set()
could be discovered right here.
xcache_set()
The xcache_set()
perform is a part of the XCache extension, which supplies a PHP opcode cache and knowledge cache. It shops a price within the XCache cache with a specified key and expiration time.
Extra info on xcache_set()
could be discovered right here.
Caching with a Database
An alternative choice for caching in PHP is to make use of a database to retailer cached knowledge. This will likely appear counterintuitive, as the first aim of caching is to scale back the variety of database accesses and enhance efficiency. Nonetheless, there are some instances the place caching knowledge in a database is likely to be helpful.
One such case is that if you could cache massive quantities of information that may not slot in reminiscence. Moreover, caching knowledge in a database could be helpful if you could entry the cached knowledge from a number of servers, because it permits for simple sharing of cached knowledge between servers.
To cache knowledge in a database, you should use a desk with no less than two columns: one for the cache key, and one for the cached knowledge. You may then use a SELECT
question to examine if the cache key exists within the desk, and an INSERT
or UPDATE
question to retailer the information within the desk.
Right here’s an instance of the way to cache knowledge in a MySQL database:
<?php
$db = new mysqli('localhost', 'username', 'password', 'database');
$cacheKey = 'cache_key';
$cachedValue = 'That is the worth to cache';
$consequence = $db->question("SELECT * FROM cache WHERE cache_key = '$cacheKey'");
if ($consequence->num_rows > 0) {
$db->question("UPDATE cache SET worth="$cachedValue" WHERE cache_key = '$cacheKey'");
} else {
$db->question("INSERT INTO cache (cache_key, worth) VALUES ('$cacheKey', '$cachedValue')");
}
$consequence = $db->question("SELECT * FROM cache WHERE cache_key = '$cacheKey'");
$row = $consequence->fetch_assoc();
$cachedValue = $row['value'];
echo $cachedValue;
This instance demonstrates the way to examine if a cache key exists within the cache desk, and if it does, the way to replace the cached worth. If the cache key doesn’t exist, a brand new row is inserted into the desk with the cache key and worth. The cached worth is then retrieved from the desk and exhibited to the person.
Conclusion
Caching is a really highly effective method for bettering the efficiency of a PHP web site or software. PHP supplies a number of choices for implementing caching, together with output buffering, caching capabilities, and caching with a database. By storing ceaselessly accessed knowledge in a brief location, we are able to cut back the variety of occasions the information must be retrieved from its supply and enhance the general pace and efficiency of a website.