A big thanks to all who took part in my last OOP thread. I’ve replaced Inheritance with Dependency Injection which does seem to make OOP life simpler. I wrote a class which was more procedural that OOP and then converted it into real OOP by offloading data (properties) to a config file. This required me to build a Config class to configure the specific objects created by the class. This turned out to be rather neat because it imports only those properties whose names match the variable names in the config file.
Suppose in a project you have a “manager” object who uses a bunch of other objects via dependency injection. All the objects can get their configuration data, i.e. properties, from the same config_manager.php file. the Config class will make sure they get only what they need. All the manager object has to do is to supply the path to the config_manager.php file.
Maybe I’m missing something but what does a “Dependency Injection Container” do that my Config class can’t handle?
<?php
class Config {
private $_pathToConfig;
private $_vars;
public function __construct($_pathToConfig, $_vars) {
$this->_pathToConfig = $_pathToConfig;
$this->_vars = $_vars;
}
public function getConfig() {
require $this->_pathToConfig;
foreach($this->_vars AS $_key=>$_value) {
$_var = $_key;
if(isset(${$_var})) {
$_result[$_key] = ${$_var};
}
}
return $_result;
}
} // class Config
?>
The calling class:
<?
class WildcardSubdomain {
// config settings
private $domain;
private $subdomains = FALSE;
private $pathToError404;
// class variables
private $rewriteFlag = FALSE;
private $host;
private $request;
private $subdomain = FALSE;
private $pathToPage;
public function __construct($include) {
$pathToConfig = "{$include}config/".strtolower(get_class()).".php";
$config = new Config($pathToConfig, get_object_vars($this));
foreach($config->getConfig() AS $key=>$value) {
$this->$key = $value;
}
}
// more class methods
} // class WildcardSubdomain
?>
I believe this has all the functionality of a Dependency Injection Container. Am I missing something?