Persistence.class.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. class Persistence
  3. {
  4. public static function getInstance()
  5. {
  6. $memcache = new Memcache();
  7. $memcache->addserver("localhost");
  8. return new Persistence(new mysqli("db-primary", "root", "", "altpath"), $memcache);
  9. }
  10. const OFFER_PATH_PAGE_SQL = "SELECT * FROM offers
  11. LEFT JOIN offer_paths ON offers.offer_id = offer_paths.offer_id
  12. LEFT JOIN path_templates ON path_templates.path_id = offer_paths.path_id
  13. LEFT JOIN templates ON templates.template_id = path_templates.template_id
  14. WHERE offers.offer_id = %s AND sequence = %s";
  15. private $mysqli;
  16. private $memcache;
  17. public function __construct(mysqli $mysqli, Memcache $memcache)
  18. {
  19. $this->mysqli = $mysqli;
  20. $this->memcache = $memcache;
  21. }
  22. public function getOfferPathPage($offerId, $page)
  23. {
  24. return $this->getFromCache($offerId, $page);
  25. }
  26. private function getFromCache($offerId, $page)
  27. {
  28. $pageData = $this->memcache->get($this->getOfferPageCacheKey($offerId, $page));
  29. if($pageData === false)
  30. {
  31. $sql = sprintf(Persistence::OFFER_PATH_PAGE_SQL, $offerId, $page);
  32. $resultData = $this->getFromDatabase($sql);
  33. if($resultData === false)
  34. {
  35. return false;
  36. }
  37. $pageData = $resultData[0];
  38. $this->memcache->add($this->getOfferPageCacheKey($offerId, $page), $pageData);
  39. }
  40. return $pageData;
  41. }
  42. private function getFromDatabase($sql)
  43. {
  44. $results = $this->mysqli->query($sql);
  45. if($results === false)
  46. {
  47. return false;
  48. }
  49. $resultData = array();
  50. while($row = $results->fetch_assoc())
  51. {
  52. $resultData[] = $row;
  53. }
  54. if(empty($resultData))
  55. {
  56. return false;
  57. }
  58. return $resultData;
  59. }
  60. private function getOfferPageCacheKey($offerId, $page)
  61. {
  62. return "page-" . $offerId . "-" . $page;
  63. }
  64. }