Last active
August 29, 2015 14:17
-
-
Save doublejosh/ee4647d6f68dd43b6180 to your computer and use it in GitHub Desktop.
Page with memcache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class PageCachable { | |
| private $memcache, | |
| $memcacheOptions = [ | |
| 'enabled' => FALSE, | |
| 'host' => 'localhost', | |
| 'port' => '11211', | |
| 'lifetime' => 10800, | |
| ]; | |
| /** | |
| * Instantiate a new Jobs page class. | |
| */ | |
| public function __construct() { | |
| $this->memcacheOptions['enabled'] = (getenv('MEMCACHE_ENABLED')) ?: $this->memcacheOptions['enabled']; | |
| } | |
| /** | |
| * Connect to cache backend. | |
| */ | |
| private function cacheConnect() { | |
| if (!class_exists('Memcache')) return FALSE; | |
| $this->memcache = new Memcache; | |
| $this->memcache->connect( | |
| $this->memcacheOptions['host'], $this->memcacheOptions['port'] | |
| ) or die ("Could not connect to cache."); | |
| return TRUE; | |
| } | |
| /** | |
| * Set content to a cache backend. | |
| * @param string $cid | |
| * @param string $content | |
| */ | |
| private function cacheSet($cid, $content) { | |
| $this->memcache->set( | |
| $cid, $content, FALSE, $this->memcacheOptions['lifetime'] | |
| ) or die ("Failed to save data to cache."); | |
| return TRUE; | |
| } | |
| /** | |
| * Get content from a cache backend. | |
| * @param string $cid | |
| * @return string|boolean | |
| */ | |
| private function cacheGet($cid) { | |
| if ($output = $this->memcache->get($cid)) { | |
| return $output; | |
| } | |
| return FALSE; | |
| } | |
| /** | |
| * Build the page from scratch. | |
| */ | |
| private function build() { | |
| // Database lookups, API calls, etc. | |
| $output = [ | |
| 'title' => 'THERE YOU GO', | |
| 'content' => 'NEATO', | |
| ]; | |
| return $output; | |
| } | |
| /** | |
| * Obtain page for template, handle alternate modes. | |
| * @return array | |
| */ | |
| public function get() { | |
| // Use a cached version (production). | |
| if ($this->memcacheOptions['enabled'] && $this->cacheConnect()) { | |
| $output = unserialize($this->cacheGet('pageVars')); | |
| if (!$output || !is_array($output)) { | |
| $output = $this->build(); | |
| $this->cacheSet('pageVars', serialize($output)); | |
| } | |
| } | |
| else { | |
| $output = $this->build(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment