I
I
Ilya2015-10-30 20:36:39
PHP
Ilya, 2015-10-30 20:36:39

How to make the application configuration available in all plug-in classes in the form of an array?

In general, there is an application configuration array:

$config = [
        'logotext' => 'USER Application Name', 
        'base_dir' => BASE_DIR, 
        'db' => [
            'file' => BASE_DIR . 'db/database.sqlite',
        ],
        'router'=> [
            'path'=>true,
            'action'=>'index',
            'rules'=> [],
        ],
    ];
// Старт приложения:
$app = new Application($config);
echo $app->run();

Application abstract class - System:
abstract class System {
public $config;
public function __construct($config=null) 
    {
        $this->_setConfig($config); // Преобразую Массив конфига в обьекты, чисто для красоты ($this->config->paramName->subParamName)
        $this->init();
    }

private function _setConfig($config) 
    {
        $this->config = $this->_toObject($config);
    }
public function router($class='Router') 
    {
        return new $class($this->config->router);    
    }

}

The main application class Application inherited from the abstract System class:
class Application extends System {
function __construct($config=null) 
    {
        parent::__construct($config);            
    }

}

Of course, I don’t know at all exactly how much this is all correctly implemented, do not scold too much. The problem is that every time you have to pass the configuration ($this->config) when creating instances of auxiliary classes inside the main Application class or in System (via the constructor), which also want to use a common configuration array. For example, I will make a new Data class, which, for example, will be of the model type, this class will need information on how to access the database
class Data {
function getConfigDSNString()
{
return; // Вернуть какую либо строку из конфигурации в качестве примера передачи конфиг массива в класс
}
}

As an option, of course, you can use a separate Config class for this, in which you can declare some static get() method and call something like Config::get('dbDSN');
What other options are there to not bind classes to configuration transfer through constructors or through an additional static class Config?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shagguboy, 2015-11-09
@shagguboy

DI

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question