這段代碼看不懂,誰能解釋一下哈 100分
本帖最後由 php_csdn1 於 2014-11-13 11:00:58 編輯
/**
* 模型執行個體化入口
*
* @param string $model_name 模型名稱
* @return obj 對象形式的返回結果
*/
function Model($model = null){
static $_cache = array();
if (!is_null($model) && isset($_cache[$model])) return $_cache[$model];
$file_name = BASE_DATA_PATH.'/model/'.$model.'.model.php';
$class_name = $model.'Model';
if (!file_exists($file_name)){
return $_cache[$model] = new Model($model);
}else{
require_once($file_name);
if (!class_exists($class_name)){
$error = 'Model Error: Class '.$class_name.' is not exists!';
throw_exception($error);
}else{
return $_cache[$model] = new $class_name();
}
}
}
------解決思路----------------------
/**
* 模型執行個體化入口
*
* @param string $model_name 模型名稱
* @return obj 對象形式的返回結果
*/
function Model($model = null){
//儲存已經執行個體化的model的數組 model名字為key 執行個體化為value
static $_cache = array();
//如果在cache儲存中存在 則直接返回對應的儲存執行個體
if (!is_null($model) && isset($_cache[$model])) return $_cache[$model];
//model儲存的檔案路徑 model需要按照 xxxxx.model.php
$file_name = BASE_DATA_PATH.'/model/'.$model.'.model.php';
//model的類型需要是 xxxxModel
$class_name = $model.'Model';
if (!file_exists($file_name)){
//如果檔案不存在(類不存在) 執行個體化一個Model的對象
return $_cache[$model] = new Model($model);
}else{
//如果檔案存在(類存在) 則包含進來
require_once($file_name);
//判斷類是否存在 不存在拋出異常
if (!class_exists($class_name)){
$error = 'Model Error: Class '.$class_name.' is not exists!';
throw_exception($error);
}else{
//存在則執行個體化 放在cache裡邊 並返回
return $_cache[$model] = new $class_name();
}
}
}
其實就是Model的執行個體化和一個對象緩衝 現在一般用autoload來實現
------解決思路----------------------
這段代碼就一個作用:返回$model的執行個體類
返回途徑有三個:
1、如果靜態變數中已經執行個體過了,就直接返回;
2、如果model目錄中存在類檔案,則執行個體化其中的類
3、如果檔案不存在,則直接返回一個此類的執行個體