Posted By

mladoux on 01/03/12


Tagged

utility


Versions (?)

Config Class


 / Published in: PHP
 

URL: http://markladoux.com

Simple class to manage configuration data stored in scripts or in a database.

  1. <?php
  2.  
  3. /**
  4.  * Config Class
  5.  *
  6.  * Simple class to manage configuration data stored in scripts or in a
  7.  * database.
  8.  *
  9.  * Requires CONFIG constant to be set to path where static
  10.  * configurations are to be stored.
  11.  *
  12.  * Database settings must be stored as an array in a config file as
  13.  * $config['database'], which must be loaded from autoload.php.
  14.  *
  15.  * autoload.php must be in the config directory.
  16.  *
  17.  * all static configurations must be loaded from the $autoload array
  18.  * which should contain the name of the config file, minus the .php file
  19.  * extension. the script will append the php file extension to the filename
  20.  * by itself.
  21.  *
  22.  * I've not included the sql, but the valuse will be stored in a database
  23.  * table named config, and the required fields are item and value. format them
  24.  * in any manner that you wish. just make sure that item is set to unique or
  25.  * primary key.
  26.  *
  27.  * Disclaimer of Warranty:
  28.  *
  29.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  30.  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  31.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  32.  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  33.  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  34.  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  35.  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  36.  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  37.  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  38.  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  39.  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40.  *
  41.  * You may redistribute this script without modifications. You may also
  42.  * distribute a modified version of this script, provided you notate that the
  43.  * script has been modified, provide a record of all changes that have been
  44.  * made, and provide a link to the original script. If you redistribute, you
  45.  * may not charge a fee for this script. You may charge a fee to support this
  46.  * script.
  47.  *
  48.  * @author Mark A. LaDoux
  49.  * @link http://markladoux.com/
  50.  * @copyright 2012 Mark LaDoux
  51.  * @version 1.0.1
  52.  *
  53.  * CHANGE LOG:
  54.  *
  55.  * [2012.01.02] CREATED SCRIPT
  56.  * [2012.01.03] EDITED FUNCTION NOT TO RELY ON INTERNAL FUNCTION FROM MY PROJECT
  57.  */
  58.  
  59. class Config {
  60.  
  61. /**************************************************************************
  62.   Class Configuration
  63.  
  64.   This section contains configuration data and initialization for the
  65.   class.
  66.   /**************************************************************************/
  67.  
  68. /**
  69.   * @param array $s_items static configuration items
  70.   * @param array $d_items dynamic configuration items
  71.   */
  72.  
  73. private static $s_items = null;
  74. private static $d_items = null;
  75. private static $con = null;
  76.  
  77. /**
  78.   * __construct
  79.   *
  80.   * initializes the class for use
  81.   *
  82.   * @access public
  83.   * @return null function does not return a result
  84.   */
  85.  
  86. public function __construct() {
  87.  
  88. // load static configs if necessary
  89. if(self::$s_items === null) self::get_static_items();
  90.  
  91. // check database connection
  92. if(self::$con === null) self::$con = self::get_db();
  93.  
  94. // load dynamic configs if necessary
  95. if( self::$d_items === null ) self::get_db_items();
  96. }
  97.  
  98. /**************************************************************************
  99.   Class Actions
  100.  
  101.   This section contains useable actions for the class
  102.   /**************************************************************************/
  103.  
  104. /**
  105.   * item
  106.   *
  107.   * retrieves an item from configuration arrays and returns the result.
  108.   *
  109.   * @access public
  110.   * @param string $name name of the key to retrieve the value of.
  111.   * @return mixed returns a result based on the key requested.
  112.   */
  113.  
  114. public static function item($name) {
  115.  
  116. // load from statics first to prevent overriding of hard coded
  117. // values.
  118. if(isset(self::$s_items[$name]))
  119. return self::$s_items[$name];
  120.  
  121. // try to load from dynamics next
  122. if(isset(self::$d_items[$name]))
  123. return self::$d_items[$name];
  124.  
  125. // if not found, return false to prevent errors.
  126. return false;
  127. }
  128.  
  129. /**
  130.   * set_item
  131.   *
  132.   * sets a configuration item in the database.
  133.   *
  134.   * @access public
  135.   * @param string $key config item to set
  136.   * @param mixed $value string or array of item to set to key
  137.   * @return bool return true if successful, false if not.
  138.   */
  139.  
  140. public static function set_item($key, $value) {
  141.  
  142. // make sure the item is not a statically configured item.
  143. if(isset(self::$s_items[$key])) {
  144. $_SESSION['ERROR'] =
  145. "Can't change statically configured value for {$key}";
  146. return false;
  147. }
  148.  
  149. // check database configuration
  150. if(self::$con === false) {
  151. $_SESSION['ERROR'] = 'Database not configured';
  152. return false;
  153. }
  154. $con = self::$con;
  155.  
  156. // prepare data for entry in the database
  157. if(is_array($value)) {
  158. $value = json_encode($value);
  159. }
  160. $value = mysqli_real_escape_string($con, $value);
  161. $key = mysqli_real_escape_string($con, $key);
  162.  
  163. // perform database check
  164. $check = $con->query("SELECT * FROM config WHERE `item`=`{$key}` LIMIT 1");
  165. if($check->num_rows > 0) {
  166. $check->close();
  167. self::update_value($key, $value);
  168. } else {
  169. $check->close();
  170. self::insert_value($key, $value);
  171. }
  172.  
  173. // update $d_items
  174. self::get_db_items();
  175.  
  176. return true;
  177. }
  178.  
  179. /**
  180.   * delete_item
  181.   *
  182.   * removes a configuration item from database
  183.   *
  184.   * @access public
  185.   * @param string $key name of the item to remove.
  186.   * @return bool return true on success, false on failure.
  187.   */
  188.  
  189. public static function delete_item($key) {
  190. if(isset(self::$s_items['$key'])) {
  191. $_SESSION['ERROR'] = 'Cannot remove static configuration data';
  192. return false;
  193. }
  194. if(self::$con === false) {
  195. $_SESSION['ERROR'] = 'Database not configured!';
  196. return false;
  197. }
  198. $con = self::$con;
  199. $key = mysqli_real_escape_string($con, $key);
  200. $con->query("DELETE FROM config WHERE item='{$key}'");
  201. self::get_db_items();
  202. return true;
  203. }
  204.  
  205. /**************************************************************************
  206.   Class Utilities
  207.  
  208.   This section contains internal functions used by the class to perform
  209.   varios actions
  210.   /**************************************************************************/
  211.  
  212. /**
  213.   * insert_value
  214.   *
  215.   * Creates a new configuration item in database
  216.   *
  217.   * @access private
  218.   * @param string $key name of the item to insert
  219.   * @param string $value value of the item to insert
  220.   * @return null does not return a result
  221.   */
  222.  
  223. private static function insert_value($key, $value) {
  224. $con = self::$con;
  225. $con->query("INSERT INTO config (item, value)
  226. VALUES('{$key}','{$value}')");
  227. }
  228.  
  229. /**
  230.   * update_value
  231.   *
  232.   * Updates existing value in database
  233.   *
  234.   * @access private
  235.   * @param string $key name of the item to update
  236.   * @param string $value new alue of the item to update
  237.   * @return null does not return a result
  238.   */
  239.  
  240. private static function update_value($key, $value) {
  241. $con = self::$con;
  242. $con->query("UPDATE config SET value = '{$value}'
  243. WHERE item = '{$key}'");
  244. }
  245.  
  246. private static function get_db() {
  247. if(isset(self::$s_items['database'])) {
  248. $db_host = $s_items['database']['hostname'];
  249. $db_user = $s_items['database']['username'];
  250. $db_pass = $s_items['database']['password'];
  251. $db_name = $s_items['database']['name'];
  252. $db_port = $s_items['database']['port'];
  253.  
  254. self::$con = new mysqli($db_host,$db_user,$db_pass,$db_name,$db_port);
  255. } else {
  256. self::$con = false;
  257. }
  258. }
  259.  
  260. /**
  261.   * get_static_items
  262.   *
  263.   * Gets static configuration data from config files and associates them
  264.   * to the $s_items configuration array.
  265.   *
  266.   * @access private
  267.   * @return null does not return a result
  268.   */
  269.  
  270. private static function get_static_items() {
  271. // load configuration
  272. if(! file_exists(CONFIG.'autoload.php'))
  273. die('Configuration autoload not present!');
  274. include CONFIG.'autoload.php';
  275. if(! isset($autoload) || ! is_array($autoload))
  276. die('Configuration autoload not properly formatted!');
  277.  
  278. // load configuration files
  279. self::$s_items = array();
  280. foreach($autoload as $load) {
  281. if(! file_exists(CONFIG.$load.'.php'))
  282. die('ERROR: '.$load.' configuration file missing!');
  283. if(! isset($config) && ! is_array($config))
  284. die('ERROR: '.$load.' configuration not properly formatted.');
  285. self::$s_items = $config;
  286. }
  287. }
  288.  
  289. /**
  290.   * get_db_items
  291.   *
  292.   * Gets dynamic configuration data from a database and associates them
  293.   * to the $d_items configuration array.
  294.   *
  295.   * @access private
  296.   * @return null does not return a result
  297.   */
  298.  
  299. private static function get_db_items() {
  300. // initialize the array
  301. self::$d_items = array();
  302.  
  303. // get items from the database
  304. if(self::$con !== false) {
  305. $con = self::$con;
  306. $query = $con->query('SELECT * FROM config');
  307. if($query->num_rows > 0) {
  308. while($row = $query::fetch_assoc()) {
  309. $item = $row['item'];
  310. $value = $row['value'];
  311.  
  312. // filter value a bit
  313. if(strtolower($value) == '{{false}}') $value = false;
  314. if(strtolower($value) == '{{true}}') $value = true;
  315. if(strtolower($value) == '{{null}}') $value = null;
  316. if(strtolower($value) == '{{empty}}') $value = '';
  317.  
  318. // check for json
  319. $is_json = (is_array(json_decode($value))) ? true : false;
  320. if($is_json) $value = json_decode($value);
  321.  
  322. // save item to array
  323. self::$d_items[$name] = $value;
  324. }
  325. }
  326.  
  327. // clean up memory
  328. $query->free();
  329. }
  330. }
  331. }

Report this snippet  

You need to login to post a comment.