According to the Memcached official website, it's a free, open source, high performance, and distributed memory object caching system. Memcached is an in-memory key-value store that can store datasets from a database or API calls.
Similarly to Redis, Memcached also helps a lot in speeding up a website. It stores the data (strings or objects) in the memory. This allows us to reduce the communication with outside resources, such as databases and or APIs.
Now, let's play a little with Memcachd in PHP. Take a look at the following code:
//Instantiate Memcached Object
$memCached = new Memcached();
//Add server
$memCached->addServer('127.0.0.1', 11211);
//Lets get some data
$data = $memCached->get('packt_title');
//Check if data is available
if($data)
{
echo $data;
}
else
{
/*No data is found. Fetch your data from any where and add to memcached */
$memCached->set('packt_title', 'Packt Publishing');
}The preceding code is a very simple example of using Memcached. The comments are written with each line of code and are self-explanatory. After instantiating a Memcached object, we have to add a Memcached server. By default, the Memcached server server runs on the localhost IP, which is 127.0.0.1, and on the port 11211. After this, we checked for some data using a key, and if it is available, we can process it (in this case, we displayed it. It can be returned, or whatever processing is required can be carried out.). If the data is not available, we can just add it. Please note that the data can come from a remote server API or from the database.