首页 > 代码库 > ecmall中static变量的使用-model模型代码设计

ecmall中static变量的使用-model模型代码设计

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
function &m($model_name, $params = array(), $is_new = false)
{
    <span style="background-color: rgb(255, 0, 0);">static $models = array();</span>
    $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());
    }
    print_r($models[$model_hash]);
    return $models[$model_hash];
}
 
/**
 * 获取一个业务模型
 *
 * @param string $model_name
 * @param array $params
 * @param bool $is_new
 * @return object
 */
function &bm($model_name, $params = array(), $is_new = false)
{
    <span style="background-color: rgb(255, 0, 0);">static $models = array();</span>
    $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];
}

使用static变量,当程序退出这段代码的时候,$model并不消失。这样减少了对象建时内存的消耗,有点类似单例模式。

比如这一段代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Model
{
    function  __construct()
    {
        echo ‘construct‘.‘<br>‘;
    }
}
 
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_name = ucfirst($model_name) . ‘Model‘;
        if ($is_new)
        {
            return new Model();
        }
        $models[$model_hash] =  new Model();
    }
    return $models[$model_hash];
}
 
$s = m(‘db‘, array(‘name‘));
$s1 = m(‘db‘, array(‘name‘));

 只执行了一次新建过程。