Eric
Eric

Reputation: 10646

PHP caching class

I'm a AS3 coder and i do a bit of php and i am having a hard time doing a static class that can cache variables.

Here's what i have so far :

<?php
class Cache {

private static $obj;

public static function getInstance() {
    if (is_null(self::$obj)){
        $obj = new stdClass();
    }
    if (!self::$instance instanceof self) { 
        self::$instance = new self;
    }
    return self::$instance;
}

public static function set($key,$value){
  self::$obj->$key = $value;
}

public static function get($key){
  return  self::$obj->$key;
}
}
?>

And i use the following to set my variable into an object of my static class :

<?php 
include 'cache.php';
$cache = new Cache();
$cache->set("foo", "bar");
?>

And this is retrieve the variable

 <?php 
include 'cache.php';
$cache = new Cache();
$echo = $cache->get("foo");
echo $echo //doesn't echo anything
?>

What am i doing wrong ? Thank you

Upvotes: 0

Views: 2646

Answers (2)

leemeichin
leemeichin

Reputation: 3379

I've adapted @prodigitalson's code above to get something rudimentary that works (and has much room for improvement):

class VarCache {
  protected static $instance;
  protected static $data = array();

  protected function __construct() {}

  public static function getInstance() {
     if(!self::$instance) {
       self:$instance = new self();
     }

     return self::$instance;
  }

  public function get($key) {
     self::getInstance();

     return isset(self::$data[$key]) ? self::$data[$key] : null;
  }

  public function set($key, $value) {
     self::getInstance();
     self::$data[$key] = $value;
  }
}

Usage

VarCache::set('foo', 'bar');
echo VarCache::get('foo');
// 'bar'

You'll want this class to be available everywhere you need it, and if you want it to persist between requests, I'd consider using Memcached or something similar, which will give you everything you need.

You could alternatively use some SPL functions, like ArrayObject, if you wanted to be clever :)

Upvotes: 1

prodigitalson
prodigitalson

Reputation: 60413

Try this:

class VarCache {
  protected $instance;
  protected $data = array();
  protected __construct() {}

  public static function getInstance()
  {
     if(!self::$instance) {
       self:$instance = new self();
     }

     return self::$instance;
  }

  public function __get($key) {
     return isset($this->data[$key]) ? $this->data[$key] : null;
  }

  public function __set($key, $value) {
     $this->data[$key] = $value;
  }
}

// usage

VarCache::getInstance()->theKey = 'somevalue';
echo VarCache::getInstance()->theKey;

Upvotes: 1

Related Questions