Skip to content

Instantly share code, notes, and snippets.

@teeyo
Created December 9, 2016 10:15
Show Gist options
  • Save teeyo/03d8aae7b44e9a26f02f41578045e803 to your computer and use it in GitHub Desktop.
Save teeyo/03d8aae7b44e9a26f02f41578045e803 to your computer and use it in GitHub Desktop.
An example of why you should use Memcached and cache in general
<?php
// database host
$host = '127.0.0.1';
// database name
$db = 'cache';
// database user
$user = 'homestead';
// the easiest password in the world
$pass = 'secret';
// database charset - which is optional
$charset = 'utf8';
// we forge the database connection string
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// and we prepare some default values for our PDO object
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// we instanciate our PDO Object
$pdo = new PDO($dsn, $user, $pass, $opt);
// Getting a Memcached instance
$memcached = new Memcached;
// Try to get a connection to the Memecached Server
$memcached->addServer('localhost', 11211) or die ("Could not connect");
// Try to get the variables from the cache
$cache_result = $memcached->get('nodes_list');
$cache_title = $memcached->get('complex_title');
// Create a SELECT Query with useless conditions just to make it run slow
$sqlQuery = "SELECT * FROM node WHERE type = 'page' AND created < NOW() + INTERVAL 120 DAY AND nid IN (SELECT nid FROM node WHERE created < NOW() + INTERVAL 120 DAY)";
// We check if we have our values in the cache before we go with the normal
if($cache_result && $cache_title) {
// Second User Request
// we get the results from the cache
$arr = $cache_result;
$title = $cache_title;
}
else
{
// First User Request
// we execute the query
$select = $pdo->prepare($sqlQuery)->execute();
// we fetch the data
$arr = $select->fetchAll();
// and we store it in the cache
$memcached->set('nodes_list', $arr);
// same for the function's result
$complex_title = get_complex_title();
$memcached->set('complex_title', $complex_title, 30);
}
// Result
// We display the very complex title
print '<h2>' . $cache_title . '</h2>';
// we then iterate over the query result to display
foreach($arr as $row)
{
// we print the data contained in the row
print '<p>' . $row['nid'] . ' - ' . $row['title'] . ' - ' . $row['type'] . '</p>';
}
// the mega complicated function which return the complicated title
function get_complex_title() {
sleep(2);
return 'It is not as complicated as it seems';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment