继这篇文章继续优化https://blog.csdn.net/fangkang7/article/details/83414935
在上文中这样的返回码是不灵活的,我们在进行下一步优化
<?php return [ 'code' => [ 'SUCCESS' => 1, 'USER_LOGIN_VALIDATE_ERROR' => -1000, 'ERROR_NO_USER' => -1001, 'ERROR_USER_START' => -1002, 'ERROR_PASSWORD' => -1003, 'ERROR_LOGIN_EXCESS_TIME_OUT' => -1005, ], 'info' => [ 1 => '操作成功', -1000 => '用户登录校验不成功', -1001 => '用户不存在', -1002 => '用户状态不对', -1003 => '用户密码错误', -1005 => '登录超过规定次数' ] ];
2.创建MessageBehavior钩子文件(自定义bahavior命令创建看https://blog.csdn.net/fangkang7/article/details/83415607)
3.获取message的信息,为了方便保存为常量
<?php namespace app\behavior; use Config; class MessageBehavior { public function run() { $codes = Config::get('message.code'); foreach ($codes as $key => $value) { define($key,$value); } } }
4.在common文件中写方法,一个是规定返回格式,一个是获取状态码信息
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: 咔咔 // +---------------------------------------------------------------------- // 应用公共文件 function ajaxRuturn($code,$data=[]){ $result = ['code' => $code , 'message' => getMessage($code)]; $result = (!empty($data)) ? $result['data'] = $data : $result; return $result; } function getMessage($code){ $info = config('message.info'); return (array_key_exists($code,$info) ? $info[$code] : '操作失败'); }
5.修改service中的代码(就是文章开始的那个图),将状态码的常量返回
<?php namespace app\service; use app\model\user\User; class UserService { public function login($username,$password) { $user = User::where(['user_name'=>$username])->find(); if(!$user){ //用户名不存在 return ERROR_NO_USER; } if($user->user_status != 1){ // 用户是否被封 return ERROR_USER_START; } if(!password_verify($password,$user->user_password)){ // 密码错误,登录失败 return ERROR_PASSWORD; } //登录成功 return SUCCESS; } }
6.修改login页面的方法
<?php namespace app\admin\controller; use think\Controller; use app\model\user\User; use app\service\UserService; use Request; use Db,Log; class Login extends Controller { private $userService; /** * 初始化 */ public function initialize() { $this->userService = new UserService; } /** * 登录 * @return \think\Response */ public function login() { if(Request::isPost()){ $username = Request::param('username'); $password = Request::param('password'); return ajaxRuturn($this->userService->login($username,$password)); } return $this->fetch(); } }
响应: