当前位置: 代码迷 >> PHP >> 挺难懂的解决方法
  详细解决方案

挺难懂的解决方法

热度:37   发布时间:2016-04-28 17:22:10.0
挺难懂的
下面这段代码如何理解呢,最好在关节点上给与解释
 * 行为模型实例
 *
 * @param string $model 模型名称
 * @return obj 对象形式的返回结果
 */
function Logic($model = null, $base_path = null){
    static $_cache = array();
    $cache_key = $model.'.'.$base_path;
    if (!is_null($model) && isset($_cache[$cache_key])) return $_cache[$cache_key];
    $base_path = $base_path == null ? BASE_DATA_PATH : $base_path;
    $file_name = $base_path.'/logic/'.$model.'.logic.php';
    $class_name = $model.'Logic';
    if (!file_exists($file_name)){
        return $_cache[$cache_key] =  new Model($model);
    }else{
        require_once($file_name);
        if (!class_exists($class_name)){
            $error = 'Logic Error:  Class '.$class_name.' is not exists!';
            throw_exception($error);
        }else{
            return $_cache[$cache_key] = new $class_name();
        }
    }
}

------解决思路----------------------

function Logic($model = null, $base_path = null){
//定义静态变量
    static $_cache = array();
//定义缓存key值
    $cache_key = $model.'.'.$base_path;
//若是静态变量中有这个模型的实例就直接返回
    if (!is_null($model) && isset($_cache[$cache_key])) return $_cache[$cache_key];
//组织类文件路径
    $base_path = $base_path == null ? BASE_DATA_PATH : $base_path;
    $file_name = $base_path.'/logic/'.$model.'.logic.php';
    $class_name = $model.'Logic';
//类文件是否存在
    if (!file_exists($file_name)){
//不存在就实例一个model
        return $_cache[$cache_key] =  new Model($model);
    }else{
//存在就引入
        require_once($file_name);
//判断是否存在 该类
        if (!class_exists($class_name)){
//不存在就抛出异常
            $error = 'Logic Error:  Class '.$class_name.' is not exists!';
            throw_exception($error);
        }else{
//存在就实例化它,存入静态数组中并返回
            return $_cache[$cache_key] = new $class_name();
        }
    }
}
  相关解决方案