开发者

Pros/Cons of when to parse a INI file

I wanted to know if parsing the INI file in the constructor is ok or is there a more optimal process?

So my current process is to pass the INI file while instantiating the class like this:

include_once('/path/to/class.php');
$bar = new Foo('/path/to/class.i开发者_运维技巧ni');
$bar->runProcess();

So in my class constructor I have something like this:

public function __construct($ini_file) {
    $ini = parse_ini_file($ini_file, true);

    // Then set all the variables I need here from the INI
    $this->variable_setting = $ini['ini_section']['ini_variable'];   
}


Doing it in the constructor is fine. However, if you don't always need it, you might want to do it in a separate method which is called only when the ini file is actually needed.


I would prefer to create a concrete interface with the config parameters you want to use. I.e.,

public function __construct($someConfigValue, $anotherConfigValue)
{
   $this->_configValue1 = $someConfigValue;
   $this->_configValue2 = $anotherConfigValue;
}

However, if you are expecting a lot of different configurations, then you are probably better off passing it an array instead.

public function __construct($config)
{
   $this->_configValue1 = $config['someConfigValue'];
   $this->_configValue2 = $config['someConfigValue'];
}

The reason why I recommend this is it shifts the responsibility of loading configurations outside of the class (which I presume your class has nothing to do with configuration loading in itself) and creates a more logical interface. Plus, it decouples config files directly from your class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜