這段代碼看不懂,哪位高手能解釋一下哈 100分

來源:互聯網
上載者:User
這段代碼看不懂,誰能解釋一下哈 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、如果檔案不存在,則直接返回一個此類的執行個體
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.