Tutorial : How to cache a resource using PHP

Attention: Les informations de ce billet sont susceptibles d'être obsolètes car vieux de plus 2 ans.
Warning: The information you are reading may be obsolete, this post was published more than 2 years ago.

In this tutorial I’ll show you how to add a smart cache system to a resource using PHP. This tutorial can be adapted to any scripting language as long as you adapt the functions too, since the logic will remain the same.

Starting point

The tutorial uses a very basic script:

  • A user sends some informations to a server;
  • Using this information, a script generate some data;
  • The data is then returned to the client encoded in Json format;

So we have 3 functions:

  • filterInput that filter incoming parameters from the client request;
  • fetchData that fetch the data using the developer business logic;
  • outputEscapedJson that encode the data to be Json outputted correctly;

For the purpose of this tutorial we will assume that those functions have been tested and they work 🙂 !

PHP default behavior

So the script is really as simple as the code below:

<?php
$params = filterInput($_GET);
$data = fetchData($params);
echo outputEscapedJson($data);

This code will work, but you have to keep in mind that PHP made some assumptions when generating the response: Continue reading