Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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';
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement