2011-04-26 256 views
1

我想知道在構造函數中解析INI文件是否正常或者是否存在更優化的過程?解析INI文件的優點/缺點

所以我目前的進程是通過INI文件,同時初始化類,就像這樣:

include_once('/path/to/class.php'); 
$bar = new Foo('/path/to/class.ini'); 
$bar->runProcess(); 

所以在我的類的構造函數我有這樣的事情:

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']; 
} 

回答

3

做這在構造函數很好。但是,如果您並不總是需要它,那麼您可能需要在單獨的方法中執行該方法,該方法僅在實際需要ini文件時調用。

+0

如果某件配置不正確,我喜歡退出該過程。 – 2011-04-26 13:47:31

+0

在這種情況下拋出異常 – ThiefMaster 2011-04-26 13:49:31

0

我寧願用你想要使用的配置參數創建一個具體的接口。即,

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

但是,如果你期待很多不同的配置,那麼你可能更好的方式是傳遞一個數組。

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

爲什麼我建議,這是它改變加載配置的課堂外的責任(我假定你的類無關與配置加載在本身),並創建一個更合乎邏輯接口的原因。另外,它可以直接從你的課程中分離配置文件。