php application global settings

前端 未结 3 2031
我在风中等你
我在风中等你 2021-01-06 09:50

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

3条回答
  •  旧时难觅i
    2021-01-06 10:44

    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...

提交回复
热议问题