ECMALL源码阅读三:模型的获取

ECMALL的模型分为两种,一种是数据库关系模型,大部分模型都是这种,一种是业务模型。业务模型继承了关系模型,但是只有业务逻辑,没有表联系。
系统中只有三个业务模型:

推荐类型 recommend;商品数据模型 goods;商品分类业务模型 gcategory;

他们的模型获取方式稍微不同,但是内部方法几乎一致。 获取业务模型:

$model_goods = & m(‘goods’);
$goods_info = $model_goods->get($goods_id);

m(‘goods’)返回的是模型对象。值得注意的是,对于PHP5来说,其实是不需要 = & 的方式的。自PHP5起,对象是引用传递而不是拷贝传递。 细节请看代码:

获取模型(model.base.php)

<?php
//获取一个模型
function &m($model_name, $params = array(), $is_new = false)
{
    static $models = array();
	//将对象名跟参数转化成唯一的字符串
    $model_hash = md5($model_name . var_export($params, true));
	//如果对象已创建,直接返回
    if ($is_new || !isset($models[$model_hash]))
    {
        $model_file = ROOT_PATH . '/includes/models/' . $model_name . 
'.model.php';
        if (!is_file($model_file))
        {
            /* 不存在该文件,则无法获取模型 */
            return false;
        }
        include_once($model_file);
        $model_name = ucfirst($model_name) . 'Model';
        if ($is_new)
        {
            return new $model_name($params, db());
        }
		//将对象保存,备用
        $models[$model_hash] = new $model_name($params, db());
    }

    return $models[$model_hash];
}

//获取一个业务模型
function &bm($model_name, $params = array(), $is_new = false)
{
    static $models = array();
    $model_hash = md5($model_name . var_export($params, true));
    if ($is_new || !isset($models[$model_hash]))
    {
        $model_file = ROOT_PATH . '/includes/models/' . $model_name . 
'.model.php';
        if (!is_file($model_file))
        {
            /* 不存在该文件,则无法获取模型 */
            return false;
        }
        include_once($model_file);
        $model_name = ucfirst($model_name) . 'BModel';
        if ($is_new)
        {
            return new $model_name($params, db());
        }
        $models[$model_hash] = new $model_name($params, db());
    }

    return $models[$model_hash];
}
?>