[ Index ]
 

Code source de PRADO 3.0.6

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/framework/Caching/ -> TSqliteCache.php (source)

   1  <?php
   2  /**
   3   * TSqliteCache class file
   4   *
   5   * @author Qiang Xue <qiang.xue@gmail.com>
   6   * @link http://www.pradosoft.com/
   7   * @copyright Copyright &copy; 2005 PradoSoft
   8   * @license http://www.pradosoft.com/license/
   9   * @version $Id: TSqliteCache.php 1397 2006-09-07 07:55:53Z wei $
  10   * @package System.Caching
  11   */
  12  
  13  /**
  14   * TSqliteCache class
  15   *
  16   * TSqliteCache implements a cache application module based on SQLite database.
  17   *
  18   * The database file is specified by the {@link setDbFile DbFile} property.
  19   * If not set, the database file will be created under the system state path.
  20   * If the specified database file does not exist, it will be created automatically.
  21   * Make sure the directory containing the specified DB file and the file itself is
  22   * writable by the Web server process.
  23   *
  24   * The following basic cache operations are implemented:
  25   * - {@link get} : retrieve the value with a key (if any) from cache
  26   * - {@link set} : store the value with a key into cache
  27   * - {@link add} : store the value only if cache does not have this key
  28   * - {@link delete} : delete the value with the specified key from cache
  29   * - {@link flush} : delete all values from cache
  30   *
  31   * Each value is associated with an expiration time. The {@link get} operation
  32   * ensures that any expired value will not be returned. The expiration time by
  33   * the number of seconds. A expiration time 0 represents never expire.
  34   *
  35   * By definition, cache does not ensure the existence of a value
  36   * even if it never expires. Cache is not meant to be an persistent storage.
  37   *
  38   * Do not use the same database file for multiple applications using TSqliteCache.
  39   * Also note, cache is shared by all user sessions of an application.
  40   *
  41   * To use this module, the sqlite PHP extension must be loaded. Note, Sqlite extension
  42   * is no longer loaded by default since PHP 5.1.
  43   *
  44   * Some usage examples of TSqliteCache are as follows,
  45   * <code>
  46   * $cache=new TSqliteCache;  // TSqliteCache may also be loaded as a Prado application module
  47   * $cache->setDbFile($dbFilePath);
  48   * $cache->init(null);
  49   * $cache->add('object',$object);
  50   * $object2=$cache->get('object');
  51   * </code>
  52   *
  53   * If loaded, TSqliteCache will register itself with {@link TApplication} as the
  54   * cache module. It can be accessed via {@link TApplication::getCache()}.
  55   *
  56   * TSqliteCache may be configured in application configuration file as follows
  57   * <code>
  58   * <module id="cache" class="System.Caching.TSqliteCache" DbFile="Application.Data.site" />
  59   * </code>
  60   * where {@link getDbFile DbFile} is a property specifying the location of the
  61   * SQLite DB file (in the namespace format).
  62   *
  63   * @author Qiang Xue <qiang.xue@gmail.com>
  64   * @version $Id: TSqliteCache.php 1397 2006-09-07 07:55:53Z wei $
  65   * @package System.Caching
  66   * @since 3.0
  67   */
  68  class TSqliteCache extends TCache
  69  {
  70      /**
  71       * name of the table storing cache data
  72       */
  73      const CACHE_TABLE='cache';
  74      /**
  75       * extension of the db file name
  76       */
  77      const DB_FILE_EXT='.db';
  78  
  79      /**
  80       * @var boolean if the module has been initialized
  81       */
  82      private $_initialized=false;
  83      /**
  84       * @var SQLiteDatabase the sqlite database instance
  85       */
  86      private $_db=null;
  87      /**
  88       * @var string the database file name
  89       */
  90      private $_file=null;
  91  
  92      /**
  93       * Destructor.
  94       * Disconnect the db connection.
  95       */
  96  	public function __destruct()
  97      {
  98          $this->_db=null;
  99      }
 100  
 101      /**
 102       * Initializes this module.
 103       * This method is required by the IModule interface. It checks if the DbFile
 104       * property is set, and creates a SQLiteDatabase instance for it.
 105       * The database or the cache table does not exist, they will be created.
 106       * Expired values are also deleted.
 107       * @param TXmlElement configuration for this module, can be null
 108       * @throws TConfigurationException if sqlite extension is not installed,
 109       *         DbFile is set invalid, or any error happens during creating database or cache table.
 110       */
 111  	public function init($config)
 112      {
 113          if(!function_exists('sqlite_open'))
 114              throw new TConfigurationException('sqlitecache_extension_required');
 115          if($this->_file===null)
 116              $this->_file=$this->getApplication()->getRuntimePath().'/sqlite.cache';
 117          $error='';
 118          if(($this->_db=new SQLiteDatabase($this->_file,0666,$error))===false)
 119              throw new TConfigurationException('sqlitecache_connection_failed',$error);
 120          if(($res=$this->_db->query('SELECT * FROM sqlite_master WHERE tbl_name=\''.self::CACHE_TABLE.'\' AND type=\'table\' LIMIT 1'))!=false)
 121          {
 122              if($res->numRows()===0)
 123              {
 124                  if($this->_db->query('CREATE TABLE '.self::CACHE_TABLE.' (key CHAR(128) PRIMARY KEY, value BLOB, expire INT)')===false)
 125                      throw new TConfigurationException('sqlitecache_table_creation_failed',sqlite_error_string(sqlite_last_error()));
 126              }
 127          }
 128          else
 129              throw new TConfigurationException('sqlitecache_table_creation_failed',sqlite_error_string(sqlite_last_error()));
 130          $this->_db->query('DELETE FROM '.self::CACHE_TABLE.' WHERE expire<>0 AND expire<'.time());
 131          $this->_initialized=true;
 132          parent::init($config);
 133      }
 134  
 135      /**
 136       * @return string database file path (in namespace form)
 137       */
 138  	public function getDbFile()
 139      {
 140          return $this->_file;
 141      }
 142  
 143      /**
 144       * @param string database file path (in namespace form)
 145       * @throws TInvalidOperationException if the module is already initialized
 146       * @throws TConfigurationException if the file is not in proper namespace format
 147       */
 148  	public function setDbFile($value)
 149      {
 150          if($this->_initialized)
 151              throw new TInvalidOperationException('sqlitecache_dbfile_unchangeable');
 152          else if(($this->_file=Prado::getPathOfNamespace($value,self::DB_FILE_EXT))===null)
 153              throw new TConfigurationException('sqlitecache_dbfile_invalid',$value);
 154      }
 155  
 156      /**
 157       * Retrieves a value from cache with a specified key.
 158       * This is the implementation of the method declared in the parent class.
 159       * @param string a unique key identifying the cached value
 160       * @return string the value stored in cache, false if the value is not in the cache or expired.
 161       */
 162  	protected function getValue($key)
 163      {
 164          $sql='SELECT value FROM '.self::CACHE_TABLE.' WHERE key=\''.$key.'\' AND (expire=0 OR expire>'.time().') LIMIT 1';
 165          if(($ret=$this->_db->query($sql))!=false && ($row=$ret->fetch(SQLITE_ASSOC))!==false)
 166              return $row['value'];
 167          else
 168              return false;
 169      }
 170  
 171      /**
 172       * Stores a value identified by a key in cache.
 173       * This is the implementation of the method declared in the parent class.
 174       *
 175       * @param string the key identifying the value to be cached
 176       * @param string the value to be cached
 177       * @param integer the number of seconds in which the cached value will expire. 0 means never expire.
 178       * @return boolean true if the value is successfully stored into cache, false otherwise
 179       */
 180  	protected function setValue($key,$value,$expire)
 181      {
 182          $sql='REPLACE INTO '.self::CACHE_TABLE.' VALUES(\''.$key.'\',\''.sqlite_escape_string($value).'\','.$expire.')';
 183          return $this->_db->query($sql)!==false;
 184      }
 185  
 186      /**
 187       * Stores a value identified by a key into cache if the cache does not contain this key.
 188       * This is the implementation of the method declared in the parent class.
 189       *
 190       * @param string the key identifying the value to be cached
 191       * @param string the value to be cached
 192       * @param integer the number of seconds in which the cached value will expire. 0 means never expire.
 193       * @return boolean true if the value is successfully stored into cache, false otherwise
 194       */
 195  	protected function addValue($key,$value,$expire)
 196      {
 197          $sql='INSERT INTO '.self::CACHE_TABLE.' VALUES(\''.$key.'\',\''.sqlite_escape_string($value).'\','.$expire.')';
 198          return @$this->_db->query($sql)!==false;
 199      }
 200  
 201      /**
 202       * Deletes a value with the specified key from cache
 203       * This is the implementation of the method declared in the parent class.
 204       * @param string the key of the value to be deleted
 205       * @return boolean if no error happens during deletion
 206       */
 207  	protected function deleteValue($key)
 208      {
 209          $sql='DELETE FROM '.self::CACHE_TABLE.' WHERE key=\''.$key.'\'';
 210          return $this->_db->query($sql)!==false;
 211      }
 212  
 213      /**
 214       * Deletes all values from cache.
 215       * Be careful of performing this operation if the cache is shared by multiple applications.
 216       */
 217  	public function flush()
 218      {
 219          return $this->_db->query('DELETE FROM '.self::CACHE_TABLE)!==false;
 220      }
 221  }
 222  
 223  ?>


Généré le : Sun Feb 25 21:07:04 2007 par Balluche grâce à PHPXref 0.7