Skip to content

Instantly share code, notes, and snippets.

@jazeabby
Last active May 19, 2020 11:50
Show Gist options
  • Save jazeabby/7edf2e1e4801672f0dc3318ab4f474b0 to your computer and use it in GitHub Desktop.
Save jazeabby/7edf2e1e4801672f0dc3318ab4f474b0 to your computer and use it in GitHub Desktop.
Initial model to for Memcache connection
<?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