* @license PHP License * @package WB * @subpackage db */ /** * Database table microcache * * Cache rows by ids to prevent multiple SELECTs of the same record in database. * * @version 0.1.0 * @package WB * @subpackage db */ class WBDatasource_TableMicroCache extends WBStdClass { /** * micro cache * @var array */ static private $cache = array(); /** * list of ids to preload * @var array */ static private $preload = array(); /** * database name * @var string */ protected $dbName = ''; /** * current table name * @var string */ private $table = '__default'; /** * constructor * * Parameter * - name database name / identifier */ public function __construct($parameter = array()) { $this->dbName = $parameter['name']; if (!isset(self::$cache[$this->dbName])) { self::$cache[$this->dbName] = array(); self::$preload[$this->dbName] = array(); } } /** * Set table * * Tell which table to use * @param string $table * @return WBDatasource_TableMicroCache */ public function setTable($table) { if (!isset(self::$cache[$this->dbName][$table])) { self::$cache[$this->dbName][$table] = array(); self::$preload[$this->dbName][$table] = array(); } $this->table = $table; return $this; } /** * Add row to cache * * Store record in cache * * @param string $id * @param array $data * @return WBDatasource_TableMicroCache */ public function add($id, $data) { self::$cache[$this->dbName][$this->table][$id] = $data; return $this; } /** * Get row from cache * * Fetch data * * @param string $id * @return array */ public function get($id) { if (isset(self::$cache[$this->dbName][$this->table][$id])) { return self::$cache[$this->dbName][$this->table][$id]; } return null; } /** * Remove row from cache * * Wipe out record in cache * * @param string $id * @return WBDatasource_TableMicroCache */ public function flush($id) { if (isset(self::$cache[$this->dbName][$this->table][$id])) { unset(self::$cache[$this->dbName][$this->table][$id]); } return $this; } /** * Add preload id * * Store id of foreign table to preload list. * * @param string $id * @return WBDatasource_TableMicroCache */ public function addPreload($id) { if (isset(self::$cache[$this->dbName][$this->table][$id])) { return $this; } self::$preload[$this->dbName][$this->table][$id] = true; return $this; } /** * Get list of preload ids * * Get list of ids to be preloaded. Flush preload list afterwards. * * @param string $id * @return array */ public function getPreload() { $ids = array_keys(self::$preload[$this->dbName][$this->table]); self::$preload[$this->dbName][$this->table] = array(); return $ids; } /** * Wipe out all the caches * * Remove cache for all tables (and databases) * * @param string $dbName */ static public function flushAll($dbName = null) { if ($dbName) { self::$cache[$dbName] = array(); self::$preload[$dbName] = array(); return; } self::$cache = array(); self::$preload = array(); } } ?>