Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. <?php
  2.  
  3. // database host
  4. $host = '127.0.0.1';
  5. // database name
  6. $db = 'cache';
  7. // database user
  8. $user = 'homestead';
  9. // the easiest password in the world
  10. $pass = 'secret';
  11. // database charset - which is optional
  12. $charset = 'utf8';
  13.  
  14. // we forge the database connection string
  15. $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
  16. // and we prepare some default values for our PDO object
  17. $opt = [
  18. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  19. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  20. PDO::ATTR_EMULATE_PREPARES => false,
  21. ];
  22. // we instanciate our PDO Object
  23. $pdo = new PDO($dsn, $user, $pass, $opt);
  24.  
  25. // Getting a Memcached instance
  26. $memcached = new Memcached;
  27. // Try to get a connection to the Memecached Server
  28. $memcached->addServer('localhost', 11211) or die ("Could not connect");
  29.  
  30. // Try to get the variables from the cache
  31. $cache_result = $memcached->get('nodes_list');
  32. $cache_title = $memcached->get('complex_title');
  33.  
  34. // Create a SELECT Query with useless conditions just to make it run slow
  35. $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)";
  36.  
  37. // We check if we have our values in the cache before we go with the normal
  38. if($cache_result && $cache_title) {
  39. // Second User Request
  40. // we get the results from the cache
  41. $arr = $cache_result;
  42. $title = $cache_title;
  43. }
  44. else
  45. {
  46. // First User Request
  47. // we execute the query
  48. $select = $pdo->prepare($sqlQuery)->execute();
  49. // we fetch the data
  50. $arr = $select->fetchAll();
  51. // and we store it in the cache
  52. $memcached->set('nodes_list', $arr);
  53.  
  54. // same for the function's result
  55. $complex_title = get_complex_title();
  56. $memcached->set('complex_title', $complex_title, 30);
  57. }
  58.  
  59. // Result
  60. // We display the very complex title
  61. print '<h2>' . $cache_title . '</h2>';
  62. // we then iterate over the query result to display
  63. foreach($arr as $row)
  64. {
  65. // we print the data contained in the row
  66. print '<p>' . $row['nid'] . ' - ' . $row['title'] . ' - ' . $row['type'] . '</p>';
  67. }
  68.  
  69. // the mega complicated function which return the complicated title
  70. function get_complex_title() {
  71. sleep(2);
  72. return 'It is not as complicated as it seems';
  73. }
  74.  
  75.  
  76. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement