Home  >  Article  >  Backend Development  >  ThinkPHP表单数据智能写入create方法实例分析_php实例

ThinkPHP表单数据智能写入create方法实例分析_php实例

WBOY
WBOYOriginal
2016-06-07 17:11:22726browse

本文实例讲述了ThinkPHP表单数据智能写入create方法。分享给大家供大家参考。具体如下:

创建数据对象 create()

除了手动构造入库的数据集之外,ThinkPHP 还提供了自动创建数据对象的 create() 方法。create() 方法将自动收集提交的表单数据并创建数据对象而无需人工干预,这在表单数据字段非常多的情况下更具优势。

将前文写入表单数据的例子用 create() 来实现:

public function insert2(){
 header("Content-Type:text/html; charset=utf-8");
 $Dao = M("User");
 if($Dao->create()){
  $Dao->password = md5($_POST["password"]);
  $Dao->regdate = time();
  if($lastInsId = $Dao->add()){
   echo "插入数据 id 为:$lastInsId";
  } else {
   echo "数据写入错误!";
  }
 }else{
  exit($Dao->getError().' [ <a href="javascript:history.back()">返 回</a> ]');
 }
}

create() 创建数据对象后,将自动收集提交过来的表单数据。而表单数据可能需要经过一定加工(例如将密码加密)才能写入数据表,所以可以对数据对象的成员属性值根据进行修改或添加去除等。

提示:create() 创建的数据对象存放于内存,在执行入库动作(add() 或 save())之前,都可以进行修改。

在上面的例子里,create()方法 的行为和 date()方法 是一致。但 date() 方法只是简单的创建数据对象,但 create() 方法还具备:

① 令牌验证
② 数据自动验证
③ 字段映射支持
④ 字段类型检查
⑤ 数据自动完成

等各种高级的数据功能,要完成这些高级数据模型功能,需要使用 D方法 实例化数据模型。ThinkPHP 提供了各种验证与填充规则供调用,具体可参见《ThinkPHP 自动验证》与《ThinkPHP 自动填充》相关文章。

自动验证与自动填充

在将表单写入数据表之前,常常会有一些对数据的检测(提交的用户名是否符合要求)与处理(如例子中的密码加密以及取得当前时间戳)。create() 方法就支持数据的自动验证与自动完成。

在 LibModel 目录下创建 UserModel.class.php 文件(User 为创建的模型对象,也对应 前缀_user 表),加入自动验证和自动填充规则:

class UserModel extends Model{
 // 自动验证设置
 protected $_validate = array(
  array('username','require','用户名必须填写!',1),
  array('email','email','邮箱格式错误!',2),
  array('username','','用户名已经存在!',0,'unique',1),
 );
 //自动填充设置
 protected $_auto = array(
  array('regdate','time',self::MODEL_INSERT,'function'),
  array('password','md5',self::MODEL_INSERT,'function'),
 );
}

将 insert2 操作更改为:

public function insert2(){
 header("Content-Type:text/html; charset=utf-8");
 $Dao = D("User");
 if($Dao->create()){
  if($lastInsId = $Dao->add()){
   echo "插入数据 id 为:$lastInsId";
  } else {
   echo "数据写入错误!";
  }
 }else{
  exit($Dao->getError().' [ <a href="javascript:history.back()">返 回</a> ]');
 }
}

如果提交的数据不符合验证要求(如用户名存在),则 create() 创建数据对象失败(返回 FALSE ),$Dao->getError() 会打印出自动验证设置规则里面设置的提示信息:用户名已经存在!

如果验证规则通过后,系统会进行自动填充设置,将表单密码进行 MD5 加密以及取得当前的时间戳填充入 create() 的数据对象。

所以 D方法 配合 create() 是非常智能而强大的,恰当运用可以达到事半功倍快速开发的目的。

提示:

① D 方法配合 create() 由于其功能强大,也就损失了一定的效率,在业务逻辑不复杂的情况下推荐 M方法+data() 模式

② create() 默认接受 POST 数据,若要接受其他类型数据,只需在参数内指定即可,如接受 GET 数据:create($_GET)

更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》及《ThinkPHP常用方法总结》

希望本文所述对大家基于ThinkPHP框架的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn