thinkphp5第30课:模型-修改器

修改器

修改器的作用是可以在数据赋值的时候自动进行转换处理

案例

学生表有一个字段:password,这个字段值需要经过md5加密处理

新增记录时,要把表单输入的密码如:123456转换成md5加密后的数据

定义Student模型时,可以写一个修改器

<?php
namespace app\index\model;
use think\Model;

class Student extends Model
{
    // 设置当前模型对应的完整数据表名称, 必须是 $table ,不能是其它名字
    protected $table = 'student';

    //状态的读取器
    public function getStatusAttr($value)
    {
        $status = [0=>'冻结',1=>'正常'];
        return $status[$value];
    }

    //创建时间的读取器
    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d',$value);

    }

    //修改器,对密码进行md5加密
    public function setPasswordAttr($value)
    {
        return md5($value);
    }
}

在控制器中保存数据

//添加
    public function add()
    {
        //将要添加的数据
        $data = [
            'no' => '1835050005',
            'name' => '王五',
            'sex' => '男',
            'age' => 20,
            'status'=>1,
            'password'=>'123456',  //原始数据采用明文
            'createtime'=>time()
        ];

        //实例化模型对象
        $stu = new Student();
        try {
            $count = $stu->save($data); //通过save()方法触发修改器
            return $count;
        } catch (Exception $ex) {
            return '添加错误,' . $ex->getMessage();
        }

    }

数据表存入的密码发生了变化(经过md5加密)

发布了136 篇原创文章 · 获赞 43 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/lsmxx/article/details/102994777