There is one topic I've struggled with for quite some time and it lies in the realm of static methods, singletons and passing parameters around for an application. I've been trying to find a way to use classes in order to pass variables around. Here's an example:
class EmployeeSettings {
private static $statuses = array();
private static $isInit = false;
private static function init() {
if(self::$isInit) return;
self::$statuses = array(
'active' => array(
'value' => 0,
'name' =>'Active'
),
'terminated' =>array(
'value' => 1,
'name' =>'Termninated'
),
'suspended' => array(
'value' => 2,
'name' =>'Suspended'
),
);
self::$isInit = true;
}
public static function getStatuses() {
self::init();
return self::$statuses;
}
public static function getStatusName($status) {
self::init();
foreach(self::getStatuses() as $ref => $info) {
if($info['value']==$status) {
return self::$statuses[$ref]['name'];
break;
}
}
}
}
This would allow me to access any parameter from EmployeeSettings
across the app.
A similar pattern can be constructed where all the application's configuration would be stored:
class CoreConfig
{
static $confArray;
public static function read($name)
{
return self::$confArray[$name];
}
public static function write($name, $value)
{
self::$confArray[$name] = $value;
}
}
Which is very "convenient" as I can get any configuration setting I need on the fly. Some would say this type of design is to be avoided for many reasons, none of which seem to tell me why they're bad and why they should be avoided. Often times it makes sense conceptually and architecturally to allow access only one instance of a particular class and I'm not sure on how to proceed any further.