基础控制器的创建
<?php
namespace app\common\controller;
/**
* 基础控制器
* 必须继承自think\Controller.php
* 这样其他的控制器只需要继承Base.php便可以继承Controller类
*/
use think\Controller;
class Base extends Controller
{
/**
* 初始化方法,继承至父类Controller类
* 创建常量,公共方法
* 在所有的方法之前被调用
*/
protected function initialize()
{
}
}
前后端公共模型创建
<?php
namespace app\common\model;
use \think\Model;
/**
* zh_user表的用户模型
*/
class User extends Model
{
//指定主键
protected $pk = 'id';
protected $table = 'zh_user';
}
用户模块验证器的创建
<?php
/**
* zh_user表的验证器
*/
namespace app\common\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'name|姓名'=>[
'require'=> 'require',
'length'=>'5,20',
'chsAphaNum'=>'chsAphaNum',//仅允许汉字,字母和数字
],
'email|邮箱'=>[
'require'=> 'require',
'length'=>'5,20',
'unique'=>'zh_user',//该字段必须在zh_user表中是唯一的
],
'mobile|手机号'=>[
'require'=> 'require',
'moblie'=>'mobile',
'unique'=>'zh_user',//该字段必须在zh_user表中是唯一的
'number'=>'number',
],
'password|密码'=>[
'require'=> 'require',
'length'=>'6,20',
'alphaNum'=>'alphaNum',//仅允许字母和数字
'confirm'=>'confirm',//自动与password_confirm字段进行自动相等验证
],
];
}
index模块下的test控制器的代码
<?php
/**
* 测试专用控制器
*/
namespace app\index\controller;
use app\common\controller\Base;
class Test extends Base
{
//测试用户的验证器
public function test1(){
//验证数据
$data = [
'name'=>'liuyuanshan',
'email'=>'peter@php.cn',
'mobile'=>'18814113479',
'password'=>'123asd',
];
$rule = 'app\common\validate\User';
$res = $this->validate($data,$rule);
if(true !== $res){
return $res;
}
return '验证通过';
}
}