You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. class MemoryCache {
  3. private $db;
  4. function __construct() {
  5. global $db;
  6. $this->db = $db;
  7. }
  8. public function write($key, $value=null, $expires='+10 minutes') {
  9. $value = is_array($value) || is_object($value) || is_bool($value) ? json_encode($value) : $value;
  10. $expireDate = date('Y-m-d H:i:s', strtotime($expires));
  11. $this->db->rawQuery('REPLACE INTO cache_memory SET cache_key = ?, cache_value = ?, cache_expire = ?', [$key, $value, $expireDate]);
  12. }
  13. public function read($key) {
  14. $return = null;
  15. $value = $this->db->where('cache_key', $key)->where('cache_expire >= NOW()')->getOne('cache_memory');
  16. if (isset($value['cache_value'])) {
  17. $value = $value['cache_value'];
  18. if ($this->isJson($value)) {
  19. $return = json_decode($value, true);
  20. } else {
  21. $return = $value;
  22. }
  23. } else {
  24. //Try to remove the expired key (if it is)
  25. $this->remove($key);
  26. }
  27. return $return;
  28. }
  29. public function remove($key) {
  30. return $this->db->where('cache_key', $key)->delete('cache_memory');
  31. }
  32. private function isJson($string) {
  33. return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
  34. }
  35. }