Simple class to manage configuration settings in a PHP application
<?php
/**
* Config Class
*
* Simple class to manage configuration data stored in scripts or in a
* database.
*
* Requires CONFIG constant to be set to path where static
* configurations are to be stored.
*
* Database settings must be stored as an array in a config file as
* $config['database'], which must be loaded from autoload.php.
*
* autoload.php must be in the config directory.
*
* all static configurations must be loaded from the $autoload array
* which should contain the name of the config file, minus the .php file
* extension. the script will append the php file extension to the filename
* by itself.
*
* I've not included the sql, but the valuse will be stored in a database
* table named config, and the required fields are item and value. format them
* in any manner that you wish. just make sure that item is set to unique or
* primary key.
*
* Disclaimer of Warranty:
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You may redistribute this script without modifications. You may also
* distribute a modified version of this script, provided you notate that the
* script has been modified, provide a record of all changes that have been
* made, and provide a link to the original script. If you redistribute, you
* may not charge a fee for this script. You may charge a fee to support this
* script.
*
* @author Mark A. LaDoux
* @link http://markladoux.com/
* @copyright 2012 Mark LaDoux
* @version 1.0.1
*
* CHANGE LOG:
*
* [2012.01.02] CREATED SCRIPT
* [2012.01.03] EDITED FUNCTION NOT TO RELY ON INTERNAL FUNCTION FROM MY PROJECT
*/
class Config {
/**************************************************************************
Class Configuration
This section contains configuration data and initialization for the
class.
/**************************************************************************/
/**
* @param array $s_items static configuration items
* @param array $d_items dynamic configuration items
*/
private static $s_items = null;
private static $d_items = null;
private static $con = null;
/**
* __construct
*
* initializes the class for use
*
* @access public
* @return null function does not return a result
*/
public function __construct() {
// load static configs if necessary
if(self::$s_items === null) self::get_static_items();
// check database connection
if(self::$con === null) self::$con = self::get_db();
// load dynamic configs if necessary
if( self::$d_items === null ) self::get_db_items();
}
/**************************************************************************
Class Actions
This section contains useable actions for the class
/**************************************************************************/
/**
* item
*
* retrieves an item from configuration arrays and returns the result.
*
* @access public
* @param string $name name of the key to retrieve the value of.
* @return mixed returns a result based on the key requested.
*/
public static function item($name) {
// load from statics first to prevent overriding of hard coded
// values.
if(isset(self::$s_items[$name]))
return self::$s_items[$name];
// try to load from dynamics next
if(isset(self::$d_items[$name]))
return self::$d_items[$name];
// if not found, return false to prevent errors.
return false;
}
/**
* set_item
*
* sets a configuration item in the database.
*
* @access public
* @param string $key config item to set
* @param mixed $value string or array of item to set to key
* @return bool return true if successful, false if not.
*/
public static function set_item($key, $value) {
// make sure the item is not a statically configured item.
if(isset(self::$s_items[$key])) {
$_SESSION['ERROR'] =
"Can't change statically configured value for {$key}";
return false;
}
// check database configuration
if(self::$con === false) {
$_SESSION['ERROR'] = 'Database not configured';
return false;
}
$con = self::$con;
// prepare data for entry in the database
if(is_array($value)) {
$value = json_encode($value);
}
$value = mysqli_real_escape_string($con, $value);
$key = mysqli_real_escape_string($con, $key);
// perform database check
$check = $con->query("SELECT * FROM config WHERE `item`=`{$key}` LIMIT 1");
if($check->num_rows > 0) {
$check->close();
self::update_value($key, $value);
} else {
$check->close();
self::insert_value($key, $value);
}
// update $d_items
self::get_db_items();
return true;
}
/**
* delete_item
*
* removes a configuration item from database
*
* @access public
* @param string $key name of the item to remove.
* @return bool return true on success, false on failure.
*/
public static function delete_item($key) {
if(isset(self::$s_items['$key'])) {
$_SESSION['ERROR'] = 'Cannot remove static configuration data';
return false;
}
if(self::$con === false) {
$_SESSION['ERROR'] = 'Database not configured!';
return false;
}
$con = self::$con;
$key = mysqli_real_escape_string($con, $key);
$con->query("DELETE FROM config WHERE item='{$key}'");
self::get_db_items();
return true;
}
/**************************************************************************
Class Utilities
This section contains internal functions used by the class to perform
varios actions
/**************************************************************************/
/**
* insert_value
*
* Creates a new configuration item in database
*
* @access private
* @param string $key name of the item to insert
* @param string $value value of the item to insert
* @return null does not return a result
*/
private static function insert_value($key, $value) {
$con = self::$con;
$con->query("INSERT INTO config (item, value)
VALUES('{$key}','{$value}')");
}
/**
* update_value
*
* Updates existing value in database
*
* @access private
* @param string $key name of the item to update
* @param string $value new alue of the item to update
* @return null does not return a result
*/
private static function update_value($key, $value) {
$con = self::$con;
$con->query("UPDATE config SET value = '{$value}'
WHERE item = '{$key}'");
}
private static function get_db() {
if(isset(self::$s_items['database'])) {
$db_host = $s_items['database']['hostname'];
$db_user = $s_items['database']['username'];
$db_pass = $s_items['database']['password'];
$db_name = $s_items['database']['name'];
$db_port = $s_items['database']['port'];
self::$con = new mysqli($db_host,$db_user,$db_pass,$db_name,$db_port);
} else {
self::$con = false;
}
}
/**
* get_static_items
*
* Gets static configuration data from config files and associates them
* to the $s_items configuration array.
*
* @access private
* @return null does not return a result
*/
private static function get_static_items() {
// load configuration
if(! file_exists(CONFIG.'autoload.php'))
die('Configuration autoload not present!');
include CONFIG.'autoload.php';
if(! isset($autoload) || ! is_array($autoload))
die('Configuration autoload not properly formatted!');
// load configuration files
self::$s_items = array();
foreach($autoload as $load) {
if(! file_exists(CONFIG.$load.'.php'))
die('ERROR: '.$load.' configuration file missing!');
if(! isset($config) && ! is_array($config))
die('ERROR: '.$load.' configuration not properly formatted.');
self::$s_items = $config;
}
}
/**
* get_db_items
*
* Gets dynamic configuration data from a database and associates them
* to the $d_items configuration array.
*
* @access private
* @return null does not return a result
*/
private static function get_db_items() {
// initialize the array
self::$d_items = array();
// get items from the database
if(self::$con !== false) {
$con = self::$con;
$query = $con->query('SELECT * FROM config');
if($query->num_rows > 0) {
while($row = $query::fetch_assoc()) {
$item = $row['item'];
$value = $row['value'];
// filter value a bit
if(strtolower($value) == '{{false}}') $value = false;
if(strtolower($value) == '{{true}}') $value = true;
if(strtolower($value) == '{{null}}') $value = null;
if(strtolower($value) == '{{empty}}') $value = '';
// check for json
$is_json = (is_array(json_decode($value))) ? true : false;
if($is_json) $value = json_decode($value);
// save item to array
self::$d_items[$name] = $value;
}
}
// clean up memory
$query->free();
}
}
}
Advertisement
