ecmall中static变量的使用-model模型代码设计
2014-06-04 11:00
309 查看
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()); } 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) { 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]; }
使用static变量,当程序退出这段代码的时候,$model并不消失。这样减少了对象建时内存的消耗,有点类似单例模式。
比如这一段代码:
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'));
只执行了一次新建过程。
相关文章推荐
- 2-1. Creating a Simple Model 使用图形界面设计器创建一个简单的模型
- WPF 应用程序使用程序的模型视图 ViewModel 设计模式
- Visual Studio 核心代码模型(Addin+CodeModel)使用心得 .
- 设计算法并写出代码移除字符串中重复的字符,不能使用额外的缓存空间。注意: 可以使用额外的一个或两个变量,但不允许额外再开一个数组拷贝。
- static 关键字 成员变量和静态变量的区别 静态使用的注意事项 静态代码块 构造代码块
- WPF 应用程序使用程序的模型视图 ViewModel 设计模式 WVVM
- Visual Studio 核心代码模型(Addin+CodeModel)使用心得
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(3)
- 网页设计 页面自动关闭代码(无需使用按钮点击关闭)
- 使用PowerDesigner 设计易读的数据库物理模型
- 可重复使用程序代码 + 可重复使用模型 = 更高的生产力
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(2)
- 可重复使用程序代码 + 可重复使用模型 = 更高的生产力
- 如何将多种设计模式结合使用(有原代码)
- 如何使用Static的变量和方法
- 使用VS自动化模型代码片段 Get DTE and UIService
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(2)
- ASP.net下使用static变量的一些体会
- [转]使用新的代码和标记模型创建真实的应用程序
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(2)