SOHOゆいちのサイト
Zend_ConfigはINIファイルを読み込んだりできて非常に便利なクラスです。ただ、生成したコンフィグクラスのインスタンスは、グローバル変数にするか、都度読み込むかする必要があります。
そこで、BsheではZend_ConfigとZend_Registryを連携させて、プログラムのどこからでもコンフィグ情報を取得できるようにしています。
前提として
実際のBsheでの実装は以下のクラスを参考にしてください。(ダウンロードはこちら)
class Bshe_Registry_Config extends Zend_Registry
{
/**
* INIファイルのフルパス情報
*
* @var string
*/
static protected $bsheInitPath = ”;/**
* INIファイルのフルパスを保存
*
* @param string $initPath
*/
public static function setInitPath($initPath)
{
self::$bsheInitPath = $initPath;
}/**
* 呼び出すコンフィグクラスを変更する場合クラス名をセット
*
* @var string
*/
static protected $bsheConfigClass = ”;/**
* INIファイルのフルパスを保存
*
* @param string $initPath
*/
public static function setConfigClass($configClass)
{
self::$bsheConfigClass = $configClass;
}/**
* コンフィグクラスを返す
*
* @return unknown_type
*/
public static function getConfigClass()
{
return self::$bsheConfigClass;
}/**
* コンフィグクラスをレジストリから取得する
* コンフィグクラスがレジストリに登録されていない場合は、予め決められたコンフィグファイルから
* コンフィグクラスを取得する。
*
* @param string $index
* @return mixed
*/
public static function getConfig($index)
{
try {
if (self::isRegistered(‘bshe_config_’ . $index)) {
return parent::get(‘bshe_config_’ . $index);
} else {
// コンフィグクラス名確定
if (self::$bsheConfigClass == ”) {
// デフォルト
$confClassName = ‘Bshe_Config_Ini’;
} else {
$confClassName = self::$bsheConfigClass;
}// コンフィグがセットされているため取得処理
if (self::$bsheInitPath != ”) {
// コンフィグパスセット済み
$tmpConfig = New $confClassName(self::$bsheInitPath, $index, array(‘allowModifications’ => true));
parent::set(‘bshe_config_’ . $index, $tmpConfig);
return $tmpConfig;
} else {
// コンフィグパスがないため設定から取得
$tmpConfig = New $confClassName(Bshe_Controller_Init::getMainPath() . ‘/init/bshe.ini’, $index, array(‘allowModifications’ => true));
parent::set(‘bshe_config_’ . $index, $tmpConfig);
return $tmpConfig;
}
}
} catch (Exception $e) {
throw $e;
}
}/**
* レジストリ上のコンフィグクラスを上書きする
*
* @param $index
* @param $config
* @return unknown_type
*/
public static function setConfig($index, $config)
{
try {
parent::set(‘bshe_config_’ . $index, $config);
return true;
} catch (Exceptio $e) {
throw $e;
}
}}
上記のようなクラスを用意して、index.phpなどの最初のアプリケーション初期化時点でiniファイルのパスをセットし、レジストリクラスをZend_Registryに登録します。
Bshe_Registry_Config::setInitPath(’/init/bshe.ini’);
Zend_Registry::setClassName(‘Bshe_Registry_Config’);
こうすることで、プログラム上の任意の箇所で
$config = Bshe_Registry_Config::getConfig(‘INI上のセクション名);
とすることで、コンフィグクラスを取り出すことができます。
www.bshe.org (created by itassist.info)