PHP Config Class
I should also add that this doesn’t seem to work with multidimensional arrays — I’m working on this. If anyone has a solution, I’d appreciate it.
1 Answer 1
You can continue to use a class if you want, but I think making a config class is overkill. Just a plain config file with constants should be good enough. It has less overhead and less abstraction. As for loading a specific config file, you can use a helper function to simulate what you have here, or just manually include it. Not everything has to be in a class.
echo Config::get( 'database.host' ); //VS echo DB_HOST; $config->load( 'config' ); //VS config( 'config' );//helper function //OR include 'config/config.php';
I think there’s something wrong with your load() method by the way. You are resetting the array each time you load a new config file. I believe it should look something like so.
static::$items[] = include "config/$filepath.php";
I’m not sure I really agree with setting $items to static. I understand you aren’t instantiating the class, but I think you should, and then just make this a normal property. Typically when I think of static properties, I think of properties that aren’t supposed to change, but you are adding to it, which seems contradictory. Maybe I’m wrong here, but this just seems odd to me. Of course I really just dislike the static keyword altogether.
You can set an array element to a variable and unset it all at the same time by using array_shift() . For example.
$filepath = array_shift( $input );
It might be worth profiling that explode/implode task and comparing it to a substr version. Assuming the array version is faster, then I would suggest changing the first delimiter to something other than a period since that’s the only one you care about. Maybe a forward slash or underscore instead? It would make needing to implode the array unnecessary.
$input = explode( '/', $key); $filepath = array_shift( $input ); $key = strval( $input );
PHP empty() should really only be used when checking arrays. A string can be determined just by querying it. For example:
Finally, I would think that the «default» return value for your getter would be NULL or FALSE. Why return the entire configuration array? This could be confusing, especially since you mentioned using multidimensional arrays. Speaking of which, what about this doesn’t work for them? The config file? The getter? What exactly is happening, and what are you expecting? Besides the things I already mentioned, I don’t see anything that would cause an issue.
Edit to clarify last comment:
Early check and return ensures less overhead and better legibility.
public static function get( $key = null ) < if( ! $key ) < return static::$items; >//etc.
I don’t condone the use of variable-variables, but its the only way I can foresee doing this. Unless you can put all of those arrays into another array, then you can access them as associative arrays.
$input = explode( '.', $key ); $filepath = array_shift( $input ); if( count( $input ) > 1 )
Creating a configuration Class in php
I am creating a system for a client that loads information from an XML file and then parses the information where needed. For this, I have got this class:
/** @return Config */ public static function Init() < return static::$init = ( null === static::$init ? new self() : static::$init ); >public function RequireFiles() < require_once static::$connectionfile; require_once static::$GWPATH . 'libraries/functions/user.loggedin.php'; >public function LoadConfig() < static::$cfg = simplexml_load_file(self::CONFIGFILEPATH); $path = static::$cfg->paths; $database = static::$cfg->database; static::$ABSPATH = (string) $path->abs; static::$GWPATH = (string) $path->gwpath; static::$CONFIGPATH = (string) $path->configpath; static::$configfile = (string) $path->configfile; static::$CONNECTIONPATH = (string) $path->connectionpath; static::$connectionfile = (string) $path->connectionfile; static::$db_hostname = (string) $database->hostname; static::$db_username = (string) $database->username; static::$db_password = (string) $database->password; static::$db_database = (string) $database->name; > public function GetLink() < if (empty(static::$link) || null === static::$link) $this->SetLink(); return static::$link; > public function SetLink() < static::$link = new Database($this->GetDBHostname(), $this->GetDBUsername(), $this->GetDBPassword(), $this->GetDBDatabase()) or die("Failed to connect to the server. Error: " . static::$link->connect_error); > private function GetDBHostname() < return static::$db_hostname; >private function GetDBUsername() < return static::$db_username; >private function GetDBPassword() < return static::$db_password; >private function GetDBDatabase() < return static::$db_database; >public function GetConfigXML($do = false) < if ($do == true) return static::$cfg; return null; >>
This is working for me, but I wanted to know if there is a better way to do this? Info:
This is used in this way:
$config = Config::Init(); $config->LoadConfig(); $config->RequireFiles(); $link = $config->GetLink();
PHP Config Class
Example usage: Example config file: The class: I should also add that this doesn’t seem to work with multidimensional arrays — I’m working on this. You might also consider setting them up as class properties, and passing them in the constructor: Solution 3: use defined variables in your config.
PHP Config Class
I’m working on a config class for PHP, where I can easily bring in config options. Any improvements/suggestions are appreciated.
Example usage:
echo Config::get('database.host'); // Returns: localhost
Example config file:
'localhost', 'username' => 'root', 'password' => '', 'database' => 'example_database' );
/** * Searches the $items array and returns the item * * @param string $item * @return string */ public static function get($key = null) < $input = explode('.', $key); $filepath = $input[0]; unset($input[0]); $key = implode('.', $input); static::load($filepath); if ( ! empty($key)) < return static::$items[$key]; >return static::$items; > >
I should also add that this doesn’t seem to work with multidimensional arrays — I’m working on this. If anyone has a solution, I’d appreciate it.
You can continue to use a class if you want, but I think making a config class is overkill. Just a plain config file with constants should be good enough. It has less overhead and less abstraction. As for loading a specific config file, you can use a helper function to simulate what you have here, or just manually include it. Not everything has to be in a class.
echo Config::get( 'database.host' ); //VS echo DB_HOST; $config->load( 'config' ); //VS config( 'config' );//helper function //OR include 'config/config.php';
I think there’s something wrong with your load() method by the way. You are resetting the array each time you load a new config file. I believe it should look something like so.
static::$items[] = include "config/$filepath.php";
I’m not sure I really agree with setting $items to static. I understand you aren’t instantiating the class, but I think you should, and then just make this a normal property. Typically when I think of static properties, I think of properties that aren’t supposed to change, but you are adding to it, which seems contradictory. Maybe I’m wrong here, but this just seems odd to me. Of course I really just dislike the static keyword altogether.
You can set an array element to a variable and unset it all at the same time by using array_shift() . For example.
$filepath = array_shift( $input );
It might be worth profiling that explode/implode task and comparing it to a substr version. Assuming the array version is faster, then I would suggest changing the first delimiter to something other than a period since that’s the only one you care about. Maybe a forward slash or underscore instead? It would make needing to implode the array unnecessary.
$input = explode( '/', $key); $filepath = array_shift( $input ); $key = strval( $input );
PHP empty() should really only be used when checking arrays. A string can be determined just by querying it. For example:
Finally, I would think that the «default» return value for your getter would be NULL or FALSE. Why return the entire configuration array? This could be confusing, especially since you mentioned using multidimensional arrays. Speaking of which, what about this doesn’t work for them? The config file? The getter? What exactly is happening, and what are you expecting? Besides the things I already mentioned, I don’t see anything that would cause an issue.
Edit to clarify last comment:
Early check and return ensures less overhead and better legibility.
public static function get( $key = null ) < if( ! $key ) < return static::$items; >//etc.
I don’t condone the use of variable-variables, but its the only way I can foresee doing this. Unless you can put all of those arrays into another array, then you can access them as associative arrays.
$input = explode( '.', $key ); $filepath = array_shift( $input ); if( count( $input ) > 1 )
How to make a config class file in PHP, Browse other questions tagged php class config or ask your own question. The Overflow Blog Exploring the interesting and strange results from our 2022 Developer Survey
Load config.php with in a class
I want to load a configuration file in a class. Here is the content of config.php
function login($email, $pwd) < $this->connect(); $result = $this->qry("SELECT uid,nameF FROM user WHERE email='".$email."' AND password='".$pwd."'"); $row=mysql_fetch_array($result); if (mysql_num_rows($result)>0) return array($row[0],$row[1]); else return array(0,0); > > ?>
include ('core/sql.php'); $obj = new sql; $data=$obj->login($email,$pwd); print_r($data);
Unable to select database!
Ignore mysql injection issue, I just need to execute the code perfectly
config.ini
server=test user=root pass=pass dbname=mydb
and with in your class have something like
class A < public $config; public function __construct() < $this->config = parse_ini_file('config.ini', true); > public function sql() < $connections = mysql_connect($this->config['server'], $this->config['user'],$this->config['password']) or die ('Unabale to connect to the database'); mysql_select_db($this->config['dbase']) or die ('Unable to select database!'); return; > >
just another way of doing it, make sure your database is correctly named too.
Additionally, if you want to use your current config.php then you will need to include in the method you are using the variables in. It cannot be used from outside that scope.
Read up on variable scope in the PHP manual.
You’ve included the file before the class declaration, at global scope, not accessible to the class method scope. If you want to use those variables inside class methods, you’ll need to either access them globally via $GLOBALS[] or the global keyword, or better yet, pass them into the function that uses them.
include ('config.php'); // Now all your variables are defined at global scope. error_reporting($__error_reporting_level); class sql < // Pass as params to the function function connect($server, $user, $password, $dbase) < $connections = mysql_connect($server, $user,$password) or die ('Unabale to connect to the database'); mysql_select_db($dbase) or die ('Unable to select database!'); return; >// etc. // etc. >
You might also consider setting them up as class properties, and passing them in the constructor:
class sql < public $server; public $user; public $password; public $dbase; public function __construct($server, $user, $password, $dbase) < $this->server = $server; $this->user = $user; // etc. $connections = mysql_connect($this->server, $this->user, $this->password); > >
use defined variables in your config.
config.ini [database] username = root password = 1 dbname = users dsn = localhost . class Database< public $koneksi; function __construct()< try< $config = parse_ini_file('config.ini'); $this->koneksi = new PDO("mysql:host=" . $config['dsn'] . ";dbname=" . $config['dbname'], $config['username'],$config['password'],array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); $this->koneksi->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); >catch(PDOException $e)< $e->getMessage(); > > >
What is the best way to save config variables in a PHP, I often switch between .NET and PHP development. With ASP.NET sites I save configuration information (e.g. connection strings, directories, application setting) in the web.config file which is appropriately protected and easy to access the values, etc.. In PHP, I solve this with a class that has static methods for each …
How to make a config class file in PHP
Is it possible to make a configuration class in PHP?
First you need to get the $GLOBALS[‘config’] then the key that has been called (for example):
echo Config::get(‘database/main/username’);
Then every ‘key’ is exploded ( a PHP function ) by a delimiter of ‘ / ‘, then every ‘key’ again is added to the main key. The main key is $GLOBALS[‘config’] which is having the whole array of configurations.
So, every key should be defined (trying foreach ) and add a ‘count’ to know what is the count of the array is My codes so far:
array( "username" => 'root', "password" => '', 'host' => '127.0.0.1', 'name' => 'thegrades' ), ); class Config < public static function get($key = null) < $count = 0; $key = explode("/", $key); if(count($key) >1) < $mainkey = $GLOBALS['config']; foreach($key as $value)< $mainkey .= [$key[$count]]; $count++; >> return $mainkey; > > var_dump(Config::get('database/host')); ?>
On way to rome, refactor this and take what you need.
array( "username" => 'root', "password" => '', 'host' => '127.0.0.1', 'name' => 'thegrades' ), ); class Config < public static function get($key = null) < $keys = explode("/", $key); $tmpref = &$GLOBALS['config']; $return = null; while($key=array_shift($keys))< if(array_key_exists($key,$tmpref))< $return = $tmpref[$key]; $tmpref = &$tmpref[$key]; >else < return null;//not found >> return $return;//found > > var_dump(Config::get('database/host'));//127.0.0.1 ?>
Can I set a PHP class property from an existing variable?, You could use e.g. the Zend Config class to read and write such files (and this class can even deal with a plain PHP array as configuration. In the end this will make your code easier to maintain. After reading other answers and comments you might also be interested in the Zend Registry class.