The following code works and does what I want, but I'd like to confirm I'm using this OOP concept correctly. I'm using the following class to get and set some configuration parameters for my program. It used $GLOBALS for this before, but I'm trying to use a singleton pattern for this instead.
Below is the Config class. Does anything jump out as aggressively stupid? Seeing as how I'm going to be including this in most files any way I figured it would make sense to throw the autoload function in there too- is this bad design?
<?php
//This class will be included for every file
//needing access to global settings and or
//the class library
spl_autoload_register(function($class){
require_once 'classes/' . $class . '.php';
});
final class Config {
private static $inst = null;
//Array to hold global settings
private static $config = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '123456',
'db' => NULL
),
'shell' => array(
'exe' => 'powershell.exe',
'args' => array(
'-NonInteractive',
'-NoProfile',
'-NoLogo',
'-Command'
)
)
);
public static function getInstance() {
if (static::$inst === null) {
static::$inst = new Config();
}
return static::$inst;
}
public function get($path=NULL) {
if($path) {
//parse path to return config
$path = explode('/', $path);
foreach($path as $element) {
if(isset(static::$config[$element])) {
static::$config = static::$config[$element];
} else {
//If specified path not exist
static::$config = false;
}
}
}
//return all configs if path NULL
return static::$config;
}
public function set($path=NULL,$value=NULL) {
if($path) {
//parse path to return config
$path = explode('/', $path);
//Modify global settings
$setting =& static::$config;
foreach($path as $element) {
$setting =& $setting[$element];
}
$setting = $value;
}
}
//Override to prevent duplicate instance
private function __construct() {}
private function __clone() {}
private function __wakeup() {}
}
I access it like so:
$aaa = Config::getInstance();
var_dump($aaa->get());
$aaa->set('mysql/host','zzzzzzzzzzzz');
var_dump($aaa->get());
I read a little bit about how singletons are less useful in php. I will research that further at some point, but for the time being I just want to make sure I'm doing this right.
const arrray
. I don't see an advantage of changing settings in code. Would on the other hand would be helpful is reading settings from a file withparse_ini_file
. Store an ini file in the root of your project and read it withparse_ini_file( $_SERVER['DOCUMENT_ROOT'/app.conf')
Make sure theapp.conf
cannot be read by others \$\endgroup\$