基类实现base
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\facade\Session;
class Base extends Controller
{
//api 统一返回数据格式
static public function showResCode($msg='', $data=[], $code=200){
$res = [
'msg'=>$msg ? $msg : '未定义消息',
'data'=>$data ? $data : []
];
return json([$res,$code]);
}
static public function showResCodeWithOutData($msg='',$code=200){
return self::showResCode($msg,[],$code);
}
protected function isLogin()
{
if(is_null(Session::get("username"))){
$this->error("请勿非法进入");
}
}
}
用户登录类实现:
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Exception;
use app\index\controller\Base;
use think\facade\Session;
class Pubuser extends Base
{
//登陆接口
public function login()
{
$param = request()->param();
$username = $param['username'];
$password = $param['password'];
$this->pubuserAdd($username,$password);
$sql = "select 1 from dbo.pubuser where status<>65536 and (username ='".$username."' or usercode ='".$username."') and password='".$password."' ";
$res = Db::query($sql);
$flag = $res ? true:false;
if($flag==true)
{
Session::set('username',$username);
return self::showResCode('操作成功',["msg"=>"登陆成功".Session::get("username"),"flag"=>true]);
}
else
{
return self::showResCode('操作成功',["msg"=>"登陆失败,密码或账号不正确","flag"=>false]);
}
}
// 自动新增用户
private function pubuserAdd($username, $password){
$sql = "select 1 from dbo.pubuser where status<>65536 and (username ='".$username."' or usercode ='".$username."')";
$res = Db::query($sql);
$flag = $res ? true:false;
if($flag === false)
{
$data = ['userName' => $username, 'userCode' => $username,'password'=>$password,'status'=>0]; //字段名称区分大小写
Db::startTrans();
try{
Db::table('pubuser')->insert($data);
Db::commit();
}catch(Exception $e){
Db::rockback();
}
}
}
// 登陆退出
public function logout()
{
$username = Session::get("username");
session(null);
return self::showResCode('操作成功',["res"=>$username."退出成功","flag"=>true]);
}
// 密码修改
public function updatePassword()
{
$this->isLogin();
$param = request()->param();
$username = $param['username'];
$password = $param['password'];
Db::startTrans();
try {
Db::table('pubuser')->where('username', $username)->update(['password' => $password]);
Db::commit();
return self::showResCode('操作成功',['res'=>"修改成功","flag"=>true]);
} catch (Exception $e) {
Db::rockback();
return self::showResCode('操作成功',['res'=>"修改失败","flag"=>false]);
}
}
}
引用:use think\facade\Session;
- 设置Session:Session::set('username',$username);
- 获取Session:Session::get('username');
步骤:
- 基类实现isLogin 判断用户是否在线登录
- 用户登录类实现Session.set
- 其他类在访问之前先调用基类方法isLogin