Last active
May 19, 2020 11:50
-
-
Save jazeabby/7edf2e1e4801672f0dc3318ab4f474b0 to your computer and use it in GitHub Desktop.
Initial model to for Memcache connection
This file contains 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 | |
namespace App/Models; | |
class CacheModel | |
{ | |
private $instance = null; | |
public function __construct() | |
{ | |
if (! class_exists('Memcached')) | |
{ | |
throw new \Exception('Memcached class does not exist'); | |
} | |
$persistent_id = defined('APP_NAME') ? APP_NAME : 'memcache_connection'; | |
$this->instance = (new Memcached($persistent_id))->addServer('localhost', '11211'); | |
} | |
/** | |
* function to set key in memcache | |
* @param $key | |
* @param $value | |
* @param $expiry optional | |
*/ | |
public function set($key, $value, $expiry = null) | |
{ | |
if (! $this->instance) | |
return false; | |
if ($expiry) | |
return $this->instance->set($key, $value, $expiry); | |
return $this->instance->set($key, $value); | |
} | |
/** | |
* function to get key from memcache | |
* @param $key | |
*/ | |
public function get($key) | |
{ | |
if (! $this->instance) | |
return false; | |
return $this->instance->get($key) ?? false; | |
} | |
/** | |
* function to delete a key from memcache | |
* @param $key | |
*/ | |
public function delete($key) | |
{ | |
if (! $this->instance) | |
return false; | |
$this->instance->delete($key); | |
} | |
/** | |
* function to delete all keys from memcache | |
*/ | |
public function flush() | |
{ | |
if (! $this->instance) | |
return false; | |
$this->instance->flush(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment