Source for file class.confighandler.php

Documentation is available at class.confighandler.php

  1. <?php
  2. /**
  3.  * Configuration storage handler classes.
  4.  *
  5.  * Includes following classes user for configuration handling:
  6.  *
  7.  * - interface IConfigBase
  8.  *   Interface definition
  9.  *
  10.  * - class ConfigBaseAbstract
  11.  *   Abstract base configuration class, other childs must extend this
  12.  *
  13.  * - class ConfigFileStorage
  14.  *   Handles configuration data in files
  15.  *
  16.  * - class ConfigDBStorage
  17.  *   Handles configuration data in a table.
  18.  *   NOTE: the table must be created before
  19.  *
  20.  * - class ConfigFactory
  21.  *   Factory class should used to get a instance of a configuration class
  22.  *
  23.  * @author      Murat Purc <murat@purc.de>
  24.  * @copyright   © Murat Purc 2008
  25.  * @date        18.04.2008
  26.  * @package     Contenido
  27.  * @subpackage  Configuration
  28.  * @todo        Error handling
  29.  */
  30.  
  31.  
  32. defined('CON_FRAMEWORK'or die('Illegal call');
  33.  
  34.  
  35. /**
  36.  * Interface definition for misc configuration handler.
  37.  *
  38.  * @author      Murat Purc <murat@purc.de>
  39.  * @package     Contenido
  40.  * @subpackage  Configuration
  41.  */
  42. interface IConfigBase {
  43.  
  44.     /**
  45.      * Method to get configuration, must be overwritten by child.
  46.      */
  47.     public function get();
  48.  
  49.     /**
  50.      * Method to set configuration, must be overwritten by child.
  51.      *
  52.      * @param  mixed  $param  Assoziative array or another type of variable
  53.      */
  54.     public function set($param);
  55.  
  56.     /**
  57.      * Method to remove configuration, must be overwritten by child.
  58.      */
  59.     public function remove();
  60.  
  61. }
  62.  
  63.  
  64. /**
  65.  * Abstract base config class. Extended classes must overwrite existing Methods.
  66.  *
  67.  * @author      Murat Purc <murat@purc.de>
  68.  * @package     Contenido
  69.  * @subpackage  Configuration
  70.  */
  71. abstract class ConfigBaseAbstract {
  72.  
  73.     /**
  74.      * Flag about occured error
  75.      * @var  bool 
  76.      */
  77.     protected $_bError = false;
  78.  
  79.     /**
  80.      * Key of configuration (could be a file or a md5 hash, depends on child class)
  81.      * @var  string 
  82.      */
  83.     protected $_key = null;
  84.  
  85.     /**
  86.      * Lifetime of cached data in seconds
  87.      * @var  int 
  88.      */
  89.     protected $_lifetime = 0;
  90.  
  91.  
  92.     /**
  93.      * Constructor of ConfigBaseAbstract, does some checks, stops further script execution if validation of
  94.      * arguments fails.
  95.      *
  96.      * @param  array  $options  Assoziative options array as follows:
  97.      *  <code>
  98.      *  $options['key']      = Configuration key, depending on child class
  99.      *  $options['lifetime'] = Lifetime of data in seconds, optional
  100.      *  </code>
  101.      * @throws  InvalidArgumentException If option key 'key' is missing or empty
  102.      */
  103.     public function __construct(array $options{
  104.         if (!isset($options['key'])) {
  105.             throw new InvalidArgumentException('ConfigBaseAbstract->ConfigBaseAbstract: Missing argument $options["key"]');
  106.         elseif ((string) $options['key'=== ''{
  107.             throw new InvalidArgumentException('ConfigBaseAbstract->ConfigBaseAbstract: Empty argument $options["key"]');
  108.         }
  109.  
  110.         $this->_key $options['key'];
  111.  
  112.         if (isset($options['lifetime']&& (int) $options['lifetime'0{
  113.             $this->_lifetime = (int) $options['lifetime'];
  114.         }
  115.     }
  116.  
  117.  
  118.     /**
  119.      * Returns remained lifetime
  120.      *
  121.      * @return  mixed  Remained lifetime or null
  122.      */
  123.     protected function getExpires({
  124.         return ($this->_lifetime 0time($this->_lifetime null;
  125.     }
  126.  
  127. }
  128.  
  129.  
  130. /**
  131.  * ConfigFileStorage to store serialized configuration in files.
  132.  *
  133.  * Usage:
  134.  * <code>
  135.  * $options['key'] = '/full/path/to/config.php';
  136.  *
  137.  * $config = ConfigFactory::get('filestorage', $options);
  138.  * </code>
  139.  *
  140.  * @author      Murat Purc <murat@purc.de>
  141.  * @package     Contenido
  142.  * @subpackage  Configuration
  143.  */
  144. class ConfigFileStorage extends ConfigBaseAbstract implements IConfigBase {
  145.  
  146.     /**
  147.      * Constructor of ConfigFileStorage, delegates parameter to parent.
  148.      *
  149.      * @param  array  $options  Assoziative options array as follows:
  150.      *  <code>
  151.      *  $options['key']      = Full path to configuration file
  152.      *  $options['lifetime'] = Lifetime of data in seconds, optional
  153.      *  </code>
  154.      */
  155.     public function __construct(array $options{
  156.         parent::__construct($options);
  157.  
  158.         if ($this->getExpires(&& filemtime($this->_key$this->getExpires()) {
  159.             $this->remove();
  160.         }
  161.     }
  162.  
  163.  
  164.     /**
  165.      * Reads content of configuration file and returns the content as a unserialized PHP variable.
  166.      *
  167.      * @return  mixed  PHP variable or nul on error
  168.      */
  169.     public function get(){
  170.         if (!is_file($this->_key)) {
  171.             return null;
  172.         }
  173.  
  174.         if ($content file_get_contents($this->_key)) {
  175.             return unserialize($content);
  176.         else {
  177.             return null;
  178.         }
  179.     }
  180.  
  181.  
  182.     /**
  183.      * Serializes passed configuration and stores it into the configuation file
  184.      *
  185.      * @return  bool  True on success otherwhise false
  186.      */
  187.     public function set($content){
  188.         // use LOCK_EX if script is running under PHP5
  189.         $flag (defined('LOCK_EX')) LOCK_EX null;
  190.         $result file_put_contents($this->_keyserialize($content)$flag);
  191.         return ($resulttrue false;
  192.     }
  193.  
  194.  
  195.     /**
  196.      * Removes (unlink) configuration file.
  197.      *
  198.      * @return  bool  True on success otherwhise false
  199.      */
  200.     public function remove(){
  201.         if (is_file($this->_key)) {
  202.             return unlink($this->_key);
  203.         }
  204.         return false;
  205.     }
  206.  
  207. }
  208.  
  209.  
  210. /**
  211.  * Class ConfigDBStorage to store serialized configuration in a table.
  212.  *
  213.  * Needs a table, create it if not exists using following statement:
  214.  * <code>
  215.  * -- {prefix} ist almost con by default
  216.  * CREATE TABLE {prefix}_configdbstorage (
  217.  *     `id` varchar(32) NOT NULL default '' COMMENT 'md5 hash as PK',
  218.  *     `value` text COMMENT 'Serialized content of configuration',
  219.  *     PRIMARY KEY (`id`)
  220.  * )
  221.  * </code>
  222.  *
  223.  * Usage:
  224.  * <code>
  225.  * // md5 hash of $options['key'] will be used as id in table {prefix}_configdbstorage
  226.  * $options['key'] = '/full/path/to/config.php';
  227.  * $config = ConfigFactory::get('dbstorage', $options);
  228.  * </code>
  229.  *
  230.  * @todo  Add caching lifetime to table
  231.  *
  232.  * @author      Murat Purc <murat@purc.de>
  233.  * @package     Contenido
  234.  * @subpackage  Configuration
  235.  */
  236. class ConfigDBStorage extends ConfigBaseAbstract implements IConfigBase {
  237.  
  238.     /**
  239.      * Database instance
  240.      * @var  DB_Contenido 
  241.      */
  242.     private $_oDB = null;
  243.  
  244.     /**
  245.      * Name of table where the configuration is stored
  246.      * @var  string 
  247.      */
  248.     private $_table = '';
  249.  
  250.  
  251.     /**
  252.      * Constructor of ConfigDBStorage, delegates parameter to parent and sets some properties
  253.      *
  254.      * @param  array  $options  Assoziative options array as follows:
  255.      *  <code>
  256.      *  $options['key'] = Normally full path to configuration file, where the md5 hash will be calculated
  257.      *  </code>
  258.      */
  259.     public function __construct(array $options{
  260.         parent::__construct($options);
  261.         $this->_key   = md5($this->_key);
  262.         $this->_table = $GLOBALS['cfg']['sql']['sqlprefix''_configdbstorage';
  263.         $this->_oDB   = new DB_Contenido();
  264.     }
  265.  
  266.  
  267.     /**
  268.      * Returns the configuration from db table
  269.      *
  270.      * @return  mixed  PHP variable or nul on error
  271.      */
  272.     public function get(){
  273.         $sql 'SELECT value FROM ' $this->_table ' WHERE id="' $this->_key '"';
  274.         $this->_oDB->query($sql);
  275.         if ($this->_oDB->next_record()) {
  276.             return unserialize($this->_oDB->f('value'));
  277.         else {
  278.             return null;
  279.         }
  280.     }
  281.  
  282.  
  283.     /**
  284.      * Serializes and writes passed configuration into the table.
  285.      *
  286.      * @return  bool  True on success otherwhise false
  287.      */
  288.     public function set($content){
  289.         $content mysql_real_escape_string(serialize($content));
  290.         if ($this->get()) {
  291.             $sql 'UPDATE ' $this->_table ' SET value="' $content '" WHERE id="' $this->_key '"';
  292.         else {
  293.             $sql 'INSERT INTO ' $this->_table ' (`id`, `value`) VALUES ("' $this->_key '", "' $content '")';
  294.         }
  295.         $result $this->_oDB->query($sql);
  296.         return ($resulttrue false;
  297.     }
  298.  
  299.  
  300.     /**
  301.      * Removes the configuration from table.
  302.      *
  303.      * @return  bool  True on success otherwhise false
  304.      */
  305.     public function remove(){
  306.         $sql 'DELETE FROM ' $this->_table ' WHERE id="' $this->_key '"';
  307.         $result $this->_oDB->query($sql);
  308.         return ($resulttrue false;
  309.     }
  310.  
  311. }
  312.  
  313.  
  314.  
  315. /**
  316.  * Factory class to get an instance of one of configuration classes
  317.  *
  318.  * <code>
  319.  * // ConfigFileStorage example
  320.  * $options['key'] = '/full/path/to/config.php';
  321.  * $config = ConfigFactory::get('filestorage', $options);
  322.  *
  323.  * // ConfigDBStorage example
  324.  * $options['key'] = '/full/path/to/config.php';
  325.  * $config = ConfigFactory::get('dbstorage', $options);
  326.  * </code>
  327.  *
  328.  * @author      Murat Purc <murat@purc.de>
  329.  * @package     Contenido
  330.  * @subpackage  Configuration
  331.  */
  332. class ConfigFactory {
  333.  
  334.     /**
  335.      * Returns a instance of desired configuration class
  336.      *
  337.      * @param   string  $name  Type of configuration ('filestorage', 'serializer' or 'dbstorage')
  338.      *                          Note: 'serializer' is deprecated, use 'filestorage' instead
  339.      * @param   array   $options  Options array
  340.      * @return  IConfigBase  A object based on a IConfigBase implementation
  341.      */
  342.     public static function get($name$options{
  343.         if ($name == 'filestorage'{
  344.             return new ConfigFileStorage($options);
  345.         elseif ($name == 'serializer'{
  346.             // @deprecated: use 'filestorage'
  347.             return new ConfigDBStorage($options);
  348.         elseif ($name == 'dbstorage'{
  349.             return new ConfigDBStorage($options);
  350.         }
  351.         return new ConfigFileStorage($options);
  352.     }
  353.  
  354. }
  355.  
  356.  
  357. /**
  358.  * Emulate file_put_contents for PHP 4
  359.  */
  360. if (!function_exists('file_put_contents'&& !defined('FILE_APPEND')) {
  361.  
  362.     /**#@+
  363.      * Constants
  364.      */
  365.     /**
  366.      * File append option for file_put_contents()
  367.      */
  368.     define('FILE_APPEND'1);
  369.  
  370.     /**
  371.      * This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
  372.      *
  373.      * @param  string  $filename  Path to the file where to write the data
  374.      * @param  mixed   $data      The data to write. Can be either a string or a array
  375.      * @param  int     $flag      Flag, supported is only FILE_APPEND (=1)
  376.      * @return mixed   Number of written bytes or false on error
  377.      */
  378.     function file_put_contents($filename$data$flag=false{
  379.         $mode ($flag == FILE_APPEND || strtoupper($flag== 'FILE_APPEND''a' 'w';
  380.         if (!$f @fopen($filename$mode)) {
  381.             return false;
  382.         }
  383.         if (is_array($data)) {
  384.             $data implode($data);
  385.         }
  386.         $bytes_written fwrite($f$data);
  387.         fclose($f);
  388.         return $bytes_written;
  389.     }
  390.  
  391. }

Documentation generated on Sun, 08 Feb 2009 22:00:24 +0100 by phpDocumentor 1.4.1