codecamp

模型分层

ThinkPHP支持模型的分层 ,除了Model层之外,我们可以项目的需要设计和创建其他的模型层。

通常情况下,不同的分层模型仍然是继承系统的\Think\Model类或其子类,所以,其基本操作和Model类的操作是一致的。

例如在Home模块的设计中需要区分数据层、逻辑层、服务层等不同的模型层,我们可以在模块目录下面创建ModelLogicService目录,把对用户表的所有模型操作分成三层:

  • 数据层:Home\Model\UserModel 用于定义数据相关的自动验证和自动完成和数据存取接口
  • 逻辑层:Home\Logic\UserLogic 用于定义用户相关的业务逻辑
  • 服务层:Home\Service\UserService 用于定义用户相关的服务接口等

三个模型层的定义如下:

Model类:Home\Model\UserModel.class.php

namespace Home\Model;
class UserModel extends \Think\Model{

}

实例化方法:D('User');

Logic类:Home\Logic\UserLogic.class.php

namespace Home\Logic;
class UserLogic extends \Think\Model{

}

实例化方法:D('User','Logic');

Api类:Home\Api\UserApi.class.php

namespace Home\Api;
class UserApi extends \Think\Model{

}

实例化方法:D('User','Api');

D方法默认操作的模型层由DEFAULT_M_LAYER参数配置,我们可以改变默认操作的模型层为Logic层,例如:

'DEFAULT_M_LAYER'       =>  'Logic', // 默认的模型层名称

这样,当我们调用:

$User = D('User');

的时候其实是实例化的 UserLogic类,而不是UserModel类。

虚拟模型
视图模型
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }