I have read almost all question I have found on StackOverflow on this topic, but could not find a straight answer.
Here is my code:
Application class
Your Application
class should not extend Settings
as there is no relationship between the two classes. Instead you should use dependency injection to include the settings into the Application
class. There is an example of this below and I recommend reading up on dependency injection.
class Settings {
// public to simplify example, you can add setters and getters
public $_env = null;
public $_cacheDir = null;
public $_config = null;
}
class Application {
protected $config;
public function setConfig($config) {
$this->config = $config;
}
}
$app = new Application();
$config = new Settings();
$config->_env = 'dev';
$config->_cacheDir = '/my/dir';
$config->_config = array(/* Config here */);
$app->setConfig($config);
As mentioned by marcelog in another answer you could use a bootstrap class to handle the injection of the config, as well as other objects, into your Application
class.
A basic example of a bootstrap class:
class Bootstrap {
protected $application;
public function __construct(Application $app) {
$this->application = $app;
}
// connivence method
public function init() {
$this->initSettings();
}
public function initSettings() {
$settings = new Settings();
$settings->_env = 'dev';
$settings->_cacheDir = '/my/dir';
$config = array(); // load config from file here
$settings->_config = config;
$this->application->setSettings($settings);
}
// other init methods
}
$app = new Application();
$bootstrap = new Bootstrap($app);
$bootstrap->init();
These are very basic examples and there is nothing stopping you from writing magic getters and setters, having the bootstrap call any method that begins with init, etc...