feeds with memcache


/ Published in: PHP
Save to your folder(s)

feed class with baseUrl and endpoint curling the target and caching on memcache


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. class Articles
  4. {
  5.  
  6. private $_content;
  7.  
  8. private $_defaultHost = 'local';
  9.  
  10. private $_baseUrl = 'http://localhost/feed_endpoint/';
  11.  
  12. private $_endpoint;
  13.  
  14. private $_memcache;
  15.  
  16. private $_settings = array(
  17. 'memcache' => array(
  18. 'local' => array(
  19. 'host' => 'localhost',
  20. 'port' => '11211'
  21. ),
  22. 'dev' => array(
  23. 'host' => 'default-memcache-location',
  24. 'port' => '11211'
  25. ),
  26. 'qa' => array(
  27. 'host' => 'qa-memcache-location',
  28. 'port' => '11211'
  29. ),
  30. 'live' => array(
  31. 'host' => 'live-memcache-location',
  32. 'port' => '11211'
  33. )
  34. )
  35. );
  36.  
  37. public function __construct()
  38. {
  39. $this->_setInstance()
  40. ->_memcacheConnect();
  41. }
  42.  
  43. public function getLastArticles() {
  44. return $this->setEndpoint('latest-articles-paginated?page=1')
  45. ->_doRequest()
  46. ->_sendResponse();
  47. }
  48.  
  49. public function setEndpoint($endpoint)
  50. {
  51. $this->_endpoint = $endpoint;
  52. return $this;
  53. }
  54.  
  55. public function getEndpoint()
  56. {
  57. return $this->_endpoint;
  58. }
  59.  
  60. private function _sendResponse()
  61. {
  62. return json_decode($this->_content);
  63. }
  64.  
  65. private function _doRequest()
  66. {
  67. $uri = $this->_baseUrl . $this->_endpoint;
  68.  
  69. $this->_content = $this->_memcache->get($uri);
  70.  
  71. if ($this->_content == false) {
  72. $ch = curl_init();
  73. curl_setopt($ch, CURLOPT_URL, $uri);
  74. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  75. $this->_content = curl_exec($ch);
  76. curl_close($ch);
  77.  
  78. $this->_memcache->set($this->_endpoint, $this->_content);
  79. }
  80.  
  81. return $this;
  82. }
  83.  
  84. private function _setInstance()
  85. {
  86. $this->_host = $this->_defaultHost; // localhost
  87.  
  88. $host = strtolower($_SERVER['HTTP_HOST']);
  89. if(strstr( $host, "-d.com") > -1 )
  90. $this->_host = "dev";
  91. else if(strstr( $host,"-q.com") > -1 )
  92. $this->_host = "qa";
  93. else if(strstr( $host,"prod.com") > -1)
  94. $this->_host = "live";
  95.  
  96. return $this;
  97. }
  98.  
  99. private function _memcacheConnect()
  100. {
  101. $this->_memcache = new Memcache;
  102.  
  103. $this->_memcache->connect(
  104. $this->_settings['memcache'][$this->_host]['host'],
  105. $this->_settings['memcache'][$this->_host]['port']
  106. ) or die ('Could not connect to memcache server');
  107.  
  108. return $this;
  109. }
  110.  
  111. }
  112.  
  113. $articles = new Articles();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.