configur自作してみようとしてみた
cakePHPの仕組み理解と、ソース読解力向上のために、bootstrap.phpで使用する
Configure::write(); と Configure::read();
を自分で実装してみたいと思います。
とりあえずConfigure::writeのソース
cake/libs/configure.php の行270
・ソース function write($config, $value = null) { $_this =& Configure::getInstance(); if (!is_array($config)) { $config = array($config =>; $value); } foreach ($config as $names => $value) { $name = $_this->;__configVarNames($names); switch (count($name)) { case 3: $_this->;{$name[0]}[$name[1]][$name[2]]] = $value; break; case 2: $_this->;{$name[0]}[$name[1]] = $value; break; case 1: $_this->;{$name[0]} = $value; break; } } }
Configure::read();
cake/libs/configure.php の行326
・ソース function read($var = 'debug') { $_this =& Configure::getInstance(); if ($var === 'debug') { if (!isset($_this->;debug)) { if (defined('DEBUG')) { $_this->debug = DEBUG; } else { $_this->debug = 0; } } return $_this->debug; } $name = $_this->__configVarNames($var); switch (count($name)) { case 3: if (isset($_this->{$name[0]}[$name[1]][$name[2]])) { return $_this->{$name[0]}[$name[1]][$name[2]]; } break; case 2: if (isset($_this->{$name[0]}[$name[1]])) { return $_this->{$name[0]}[$name[1]]; } break; case 1: if (isset($_this->{$name[0]})) { return $_this->{$name[0]}; } break; } return null; }
・まずは、cake/libs/configure.php と同じ階層に任意の名前でphpファイルを作成します
class 任意ファイルの先頭を大文字にしたもの extends Object {}
例)
megane.phpを作成したら、class Megane extends ・・・
・bootstrap.phpで読み込めるようにcakeフォルダのbootstrp.phpを変更します。
if (!isset($bootstrap)) {
require CORE_PATH . 'cake' . DS . 'basics.php';
$TIME_START = getMicrotime();
require CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php';
require LIBS . 'object.php';
require LIBS . 'inflector.php';require LIBS . 'configure.php';
require LIBS . 'megane.php';
}
require LIBS . 'cache.php';
Configure::getInstance();
Megane::getInstance();
$url = null;require CAKE . 'dispatcher.php';
これで、megane.phpで記述したメソッドが、コントローラー名のbootstrap.phpで
Megane::メソッド名(); と記述するだけで使用できるようになります。
megane.phpの中身
こんなんでよいのかなー・・・?//getInstanceはインスタンス化の為に必要なので、記述します。Bootstrap.phpでもつかってます。
function &getInstance($boot = true) {
static $instance = array();
if (!$instance) {
$instance[0] =& new Megane();
}
return $instance[0];
}//連想配列で、$_this->configにwriteしたいデータを書き込み
function write($config, $value = null) {
$_this =& Megane::getInstance();
$_this->config = array($config => $value);
return null;}
//指定した名前のデータがあればそのデータを返す
function read($var = 'debug') {
$_this =& Megane::getInstance();
if(isset($_this->config[$var])){
return $_this->config[$var];
}
return null;
}
}
?>
上をSingletonパターンという
Singleton パターンを用いると、そのクラスのインスタンスが1つしか生成されないことを保証することができる!
インスタンス化の書式らしい。
$_this =& Megane::getInstance();=& は参照。代入と違い、参照元の値も一緒に変更される。
「::」はインスタンス化無しでstaticなメソッドを実行ということ?なのか???