企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一、Session * 要使用`Session`类必须使用门面方式(`think\facade\Session`)调用 * 新版本不支持操作原生`$_SESSION`数组和所有`session_`开头的函数,只能通过Session类(或者助手函数)来操作 1、配置文件 session.php ~~~ return [     // session name     'name'           => 'PHPSESSID',     // SESSION_ID的提交变量,解决flash上传跨域     'var_session_id' => '',     // 驱动方式 支持file cache     'type'           => 'file',     // 存储连接标识 当type使用cache的时候有效     'store'          => null,     // 过期时间     'expire'         => 1440,     // 前缀     'prefix'         => '', ]; ~~~ 2、开启Session * 中间件`app\middleware.php`文件 ~~~ \think\middleware\SessionInit::class ~~~ 3、设置 * session 支持多级数组操作 ~~~ Session::set('name','欧阳克'); // Session数组 Session::set('admin.name','欧阳克'); Session::set('admin.uid',1); ~~~ 4、读取 ~~~ // 获取全部Session Session::all(); // 获取Session中name的值 Session::get('name'); ~~~ 5、删除 ~~~ Session::delete('name'); ~~~ 6、取值并删除 ~~~ Session::pull('name'); ~~~ 7、登陆示例 * 新建login.php文件 ~~~ namespace app\controller; use think\facade\View; use think\facade\Db; use think\facade\Request; use think\facade\Session; class Login{     public function index(){         if(Request::method() == 'POST'){             $all = Request::param();             $admin = Db::table('shop_admin')->where('account',$all['account'])->find();             if(empty($admin)){                 echo json_encode(['code'=>1,'msg'=>'未找到管理员']);                 exit;             }             if(md5($all['pwd']) != $admin['password']){                 echo json_encode(['code'=>1,'msg'=>'密码错误']);                 exit;             }             Session::set('uid',$admin['uid']);             Session::set('account',$admin['account']);             echo json_encode(['code'=>0,'msg'=>'登陆成功']) ;         }else{             $title = '商城';             View::assign([                 'title'  => $title             ]);             return View::fetch();         }     } } ~~~ * 新建Login/index.html文件 ~~~ <!DOCTYPE html> <html> <head>     <title>登录</title>     <link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css">     <script type="text/javascript" src="/static/layui/layui.js"></script> </head> <body style="background: #1E9FFF">     <div style="position: absolute; left:50%;top:50%;width: 500px;margin-left: -250px;margin-top: -200px;">         <div style="background: #ffffff;padding: 20px;border-radius: 4px;box-shadow: 5px 5px 20px #444444;">             <form class="layui-form">                 <div class="layui-form-item" style="color:gray;">                     <h2>{$title}--后台管理系统</h2>                 </div>                 <hr>                 <div class="layui-form-item">                     <label class="layui-form-label">用户名</label>                     <div class="layui-input-block">                         <input type="text" id="account" class="layui-input">                     </div>                 </div>                 <div class="layui-form-item">                     <label class="layui-form-label">密&nbsp;&nbsp;&nbsp;&nbsp;码</label>                     <div class="layui-input-block">                         <input type="password" id="password" class="layui-input">                     </div>                 </div>                 <div class="layui-form-item">                     <div class="layui-input-block">                         <button type="button" class="layui-btn" onclick="dologin()">登录</button>                     </div>                 </div>             </form>         </div>     </div>     <script type="text/javascript">         layui.use(['layer'],function(){             $ = layui.jquery;             layer = layui.layer;             // 用户名控件获取焦点             $('#account').focus();             // 回车登录             $('input').keydown(function(e){                 if(e.keyCode == 13){                     dologin();                 }             });         });         function dologin(){             var account = $.trim($('#account').val());             var pwd = $.trim($('#password').val());             if(account == ''){                 layer.alert('请输入用户名',{icon:2});                 return;             }             if(pwd == ''){                 layer.alert('请输入密码',{icon:2});                 return;             }             $.post('/index.php/login/index',{'account':account,'pwd':pwd},function(res){                 if(res.code>0){                     layer.alert(res.msg,{icon:2});                 }else{                     layer.msg(res.msg);                     setTimeout(function(){window.location.href = '/index.php/index/index'},1000);                 }             },'json');         }     </script> </body> </html> ~~~ * index/index.html文件 ~~~ use think\facade\Session; public function index(){     $title = '商城';     $session = Session::all();     if(empty($session['uid'])){         echo '<script type="text/javascript">alert("请登录!");window.location.href = "/index.php/login/index"; </script>';         exit;     }     $login = $session['account'];     # 左侧菜单     $menu = Db::table('shop_menu')->where('fid',0)->select();     $left = $menu->toArray();     foreach($left as &$left_v){         $left_v['lists'] = Db::table('shop_menu')->where('fid',$left_v['id'])->select();     }     # 右侧列表     $param = Request::param();     if(isset($param['status']) && $param['status'] == 1){         $where['status'] = 1;     }else if(isset($param['status']) && $param['status'] == 2){         $where['status'] = 2;     }else{         $where = true;     }     $p = isset($param['p']) ? $param['p'] : 1;     $db = new Goods();     $order = [         'add_time DESC',         'id DESC'     ];     $right = $db->get_all($where,$order,$p,5);     View::assign([         'title'  => $title,         'login' => $login,         'left' => $left,         'right' => $right['data'],         'count' => $right['count'],         'p' => $p,         'status' => isset($param['status']) ? $param['status'] : 0     ]);     return View::fetch(); } ~~~ ## 二、Cookie * 要使用Cookie类必须使用门面方式(`think\facade\Cookie`)调用 * 配置文件位于配置目录下的cookie.php文件,无需手动初始化,系统会在调用之前自动进行Cookie初始化工作 1、使用 Cookie ~~~ // 设置Cookie 有效期为 3600秒 Cookie::set('name', '欧阳克', 3600); // 永久保存Cookie Cookie::forever('name', '欧阳克'); //删除cookie Cookie::delete('name'); // 读取某个cookie数据 Cookie::get('name'); ~~~ 2、Cookie 配置文件 * config 目录下 cookie.php 文件 ~~~ return [     // cookie 保存时间     'expire'    => 0,     // cookie 保存路径     'path'      => '/',     // cookie 有效域名     'domain'    => '',     //  cookie 启用安全传输     'secure'    => false,     // httponly设置     'httponly'  => false,     // 是否使用 setcookie     'setcookie' => true, ]; ~~~ ## 三、缓存 * 要使用缓存必须使用门面方式(`think\facade\Cache`)调用 * 内置支持的缓存类型包括`file`、`memcache`、`wincache`、`sqlite`、`redis` 1、使用缓存 ~~~ // 缓存在3600秒之后过期 Cache::set('number', 10, 3600); // number自增(步进值为3) Cache::inc('number',3); // number自减(步进值为1) Cache::dec('number'); // 获取缓存 Cache::get('number'); // 删除缓存 Cache::delete('number'); // push 追加缓存 Cache::set('name', ['欧阳克','朱老师']); Cache::push('name', '西门大官人'); // 获取并删除缓存 Cache::pull('name'); // 清空缓存 Cache::clear(); ~~~ 2、缓存配置文件 * config 目录下 cache.php 文件 ~~~ return [     // 默认缓存驱动     'default' => 'file',     // 缓存连接方式配置     'stores'  => [         'file' => [             // 驱动方式             'type'       => 'File',             // 缓存保存目录             'path'       => '',             // 缓存前缀             'prefix'     => '',             // 缓存有效期 0表示永久缓存             'expire'     => 0,             // 缓存标签前缀             'tag_prefix' => 'tag:',             // 序列化机制 例如 ['serialize', 'unserialize']             'serialize'  => [],         ],         // redis缓存         'redis'   =>  [             // 驱动方式             'type'   => 'redis',             // 服务器地址             'host'   => '127.0.0.1',         ],         // 更多的缓存连接     ], ]; ~~~ ## 四、公用控制器 * `BaseController.php`默认基础控制器类 ~~~ use think\facade\View; use think\facade\Db; use think\facade\Session; public function initialize(){     $session = Session::all();     if(empty($session['uid'])){         echo '<script type="text/javascript">alert("请登录!");window.location.href = "/index.php/login/index"; </script>';         exit;     }     $login = $session['account'];     # 左侧菜单     $menu = Db::table('shop_menu')->where('fid',0)->select();     $left = $menu->toArray();     foreach($left as &$left_v){         $left_v['lists'] = Db::table('shop_menu')->where('fid',$left_v['id'])->select();     }     View::assign([         'login' => $login,         'left' => $left,     ]); } Index/Index.php namespace app\controller; use app\BaseController; use think\facade\View; use think\facade\Db; use think\facade\Request; use app\model\Goods; class Index extends BaseController{     public function index(){         $title = '商城';         # 右侧列表         $param = Request::param();         if(isset($param['status']) && $param['status'] == 1){             $where['status'] = 1;         }else if(isset($param['status']) && $param['status'] == 2){             $where['status'] = 2;         }else{             $where = true;         }         $p = isset($param['p']) ? $param['p'] : 1;         $db = new Goods();         $order = [             'add_time DESC',             'id DESC'         ];         $right = $db->get_all($where,$order,$p,5);         View::assign([             'title'  => $title,             'right' => $right['data'],             'count' => $right['count'],             'p' => $p,             'status' => isset($param['status']) ? $param['status'] : 0         ]);         return View::fetch();     } } ~~~ ## 五、门面 Facade * 门面为容器中的(动态)类提供了一个静态调用接口,相比于传统的静态方法调用, 带来了更好的可测试性和扩展性,你可以为任何的非静态类库定义一个`facade`类 (动态)类库Facade类think\Appthink\facade\Appthink\Cachethink\facade\Cachethink\Configthink\facade\Configthink\Cookiethink\facade\Cookiethink\Dbthink\facade\Dbthink\Env&nbsp;think\facade\Envthink\Eventthink\facade\Eventthink\Filesystemthink\facade\Filesystemthink\Lang&nbsp;think\facade\Langthink\Log&nbsp;think\facade\Logthink\Middlewarethink\facade\Middlewarethink\Requestthink\facade\Requestthink\Responsethink\facade\Responsethink\Routethink\facade\Routethink\Sessionthink\facade\Sessionthink\Validatethink\facade\Validatethink\View&nbsp;think\facade\View  1、Facade类 * 门面为容器中的(动态)类提供了一个静态调用接口,相比于传统的静态方法调用,带来了更好的可测试性和扩展性 * 系统已经为大部分核心类库定义了Facade,所以你可以通过Facade来访问这些系统类 ~~~ use think\facade\App; use think\facade\Db; use think\facade\View; use think\facade\Request; use think\facade\Session; class Index{     public function index(){         // 数据库操作         $select = Db::table('shop_goods')->select();         // 请求对象         $param = Request::param();         // Session         $session = Session::all();         // 视图         return View::fetch();     } } ~~~ 2、(动态)类库 ~~~ use think\App; use think\Db; use think\View; use think\Request; use think\Session; class Index{     public function index(View $view,Db $db){         $select = $db->table('shop_goods')->select();         $view->assign([             'name' => '欧阳克',             'select' => $select         ]);         return $view->fetch();     } } ~~~ ## 六、助手函数 * Thinkphp 系统为一些常用的操作方法封装了助手函数 助手函数描述abort&nbsp;中断执行并发送HTTP状态码app&nbsp;快速获取容器中的实例 支持依赖注入bind&nbsp;快速绑定对象实例cache&nbsp;缓存管理class_basename&nbsp;获取类名(不包含命名空间)class_uses_recursive&nbsp;获取一个类里所有用到的traitconfig获取和设置配置参数cookie&nbsp;Cookie管理download&nbsp;获取\think\response\Download对象实例dump&nbsp;浏览器友好的变量输出env&nbsp;获取环境变量event&nbsp;触发事件halt&nbsp;变量调试输出并中断执行input&nbsp;获取输入数据 支持默认值和过滤invoke&nbsp;调用反射执行callable 支持依赖注入json&nbsp;JSON数据输出jsonpJSONP数据输出lang&nbsp;获取语言变量值parse_name&nbsp;字符串命名风格转换redirect&nbsp;重定向输出request&nbsp;获取当前Request对象response&nbsp;实例化Response对象session&nbsp;Session管理token&nbsp;生成表单令牌输出trace&nbsp;记录日志信息trait_uses_recursive&nbsp;获取一个trait里所有引用到的traiturl&nbsp;Url生成validate&nbsp;实例化验证器view&nbsp;渲染模板输出display&nbsp;渲染内容输出xml&nbsp;XML数据输出app_path&nbsp;当前应用目录base_path&nbsp;应用基础目录config_path&nbsp;应用配置目录public_path&nbsp;web根目录root_path&nbsp;应用根目录runtime_path&nbsp;应用运行时目录 > > // 获取输入数据,跟Request::param()效果一样 > > $param = input(); > > // 变量调试输出并中断执行 > > $shop = Db::table('shop\_goods')->select(); > > halt($shop); > > // 渲染模板输出,跟View::fetch()效果一样 > > return view(); ## 七、调试 1、调试模式 和 Trace调试 * 根目录里`.env`文件 > // 开启调试模式 和 Trace调试 > > APP\_DEBUG = true 备:正式部署后关闭调试模式 2、变量调试 * ThinPHP内置了`dump`调试方法 > $shop = Db::table('shop\_goods')->select(); > > dump($shop);