ThinkPHP6.0 雜項(xiàng)
ThinkPHP6.0 雜項(xiàng)
一、Session
要使用
Session
類必須使用門面方式(think\facade\Session
)調(diào)用新版本不支持操作原生
$_SESSION
數(shù)組和所有session_
開頭的函數(shù),只能通過Session類(或者助手函數(shù))來操作
1、配置文件 session.php
return [ // session name 'name' => 'PHPSESSID', // SESSION_ID的提交變量,解決flash上傳跨域 'var_session_id' => '', // 驅(qū)動(dòng)方式 支持file cache 'type' => 'file', // 存儲(chǔ)連接標(biāo)識(shí) 當(dāng)type使用cache的時(shí)候有效 'store' => null, // 過期時(shí)間 'expire' => 1440, // 前綴 'prefix' => '', ];
2、開啟Session
中間件
app\middleware.php
文件
\think\middleware\SessionInit::class
3、設(shè)置
session 支持多級(jí)數(shù)組操作
Session::set('name','歐陽克'); // Session數(shù)組 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'=>'密碼錯(cuò)誤']); 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}--后臺(tái)管理系統(tǒng)</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">密 碼</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; // 用戶名控件獲取焦點(diǎn) $('#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('請(qǐng)輸入用戶名',{icon:2}); return; } if(pwd == ''){ layer.alert('請(qǐng)輸入密碼',{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("請(qǐng)登錄!");window.location.href = "/index.php/login/index"; </script>'; exit; } $login = $session['account']; # 左側(cè)菜單 $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(); } # 右側(cè)列表 $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
)調(diào)用配置文件位于配置目錄下的cookie.php文件,無需手動(dòng)初始化,系統(tǒng)會(huì)在調(diào)用之前自動(dòng)進(jìn)行Cookie初始化工作
1、使用 Cookie
// 設(shè)置Cookie 有效期為 3600秒 Cookie::set('name', '歐陽克', 3600); // 永久保存Cookie Cookie::forever('name', '歐陽克'); //刪除cookie Cookie::delete('name'); // 讀取某個(gè)cookie數(shù)據(jù) Cookie::get('name');
2、Cookie 配置文件
config 目錄下 cookie.php 文件
return [ // cookie 保存時(shí)間 'expire' => 0, // cookie 保存路徑 'path' => '/', // cookie 有效域名 'domain' => '', // cookie 啟用安全傳輸 'secure' => false, // httponly設(shè)置 'httponly' => false, // 是否使用 setcookie 'setcookie' => true, ];
三、緩存
要使用緩存必須使用門面方式(
think\facade\Cache
)調(diào)用內(nèi)置支持的緩存類型包括
file
、memcache
、wincache
、sqlite
、redis
1、使用緩存
// 緩存在3600秒之后過期 Cache::set('number', 10, 3600); // number自增(步進(jìn)值為3) Cache::inc('number',3); // number自減(步進(jìn)值為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 [ // 默認(rèn)緩存驅(qū)動(dòng) 'default' => 'file', // 緩存連接方式配置 'stores' => [ 'file' => [ // 驅(qū)動(dòng)方式 'type' => 'File', // 緩存保存目錄 'path' => '', // 緩存前綴 'prefix' => '', // 緩存有效期 0表示永久緩存 'expire' => 0, // 緩存標(biāo)簽前綴 'tag_prefix' => 'tag:', // 序列化機(jī)制 例如 ['serialize', 'unserialize'] 'serialize' => [], ], // redis緩存 'redis' => [ // 驅(qū)動(dòng)方式 'type' => 'redis', // 服務(wù)器地址 'host' => '127.0.0.1', ], // 更多的緩存連接 ], ];
四、公用控制器
BaseController.php
默認(rèn)基礎(chǔ)控制器類
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("請(qǐng)登錄!");window.location.href = "/index.php/login/index"; </script>'; exit; } $login = $session['account']; # 左側(cè)菜單 $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 = '商城'; # 右側(cè)列表 $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
門面為容器中的(動(dòng)態(tài))類提供了一個(gè)靜態(tài)調(diào)用接口,相比于傳統(tǒng)的靜態(tài)方法調(diào)用, 帶來了更好的可測試性和擴(kuò)展性,你可以為任何的非靜態(tài)類庫定義一個(gè)
facade
類
(動(dòng)態(tài))類庫 | Facade類 |
think\App | think\facade\App |
think\Cache | think\facade\Cache |
think\Config | think\facade\Config |
think\Cookie | think\facade\Cookie |
think\Db | think\facade\Db |
think\Env | think\facade\Env |
think\Event | think\facade\Event |
think\Filesystem | think\facade\Filesystem |
think\Lang | think\facade\Lang |
think\Log | think\facade\Log |
think\Middleware | think\facade\Middleware |
think\Request | think\facade\Request |
think\Response | think\facade\Response |
think\Route | think\facade\Route |
think\Session | think\facade\Session |
think\Validate | think\facade\Validate |
think\View | think\facade\View |
1、Facade類
門面為容器中的(動(dòng)態(tài))類提供了一個(gè)靜態(tài)調(diào)用接口,相比于傳統(tǒng)的靜態(tài)方法調(diào)用,帶來了更好的可測試性和擴(kuò)展性
系統(tǒng)已經(jīng)為大部分核心類庫定義了Facade,所以你可以通過Facade來訪問這些系統(tǒng)類
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(){ // 數(shù)據(jù)庫操作 $select = Db::table('shop_goods')->select(); // 請(qǐng)求對(duì)象 $param = Request::param(); // Session $session = Session::all(); // 視圖 return View::fetch(); } }
2、(動(dòng)態(tài))類庫
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(); } }
六、助手函數(shù)
Thinkphp 系統(tǒng)為一些常用的操作方法封裝了助手函數(shù)
助手函數(shù) | 描述 |
abort | 中斷執(zhí)行并發(fā)送HTTP狀態(tài)碼 |
app | 快速獲取容器中的實(shí)例 支持依賴注入 |
bind | 快速綁定對(duì)象實(shí)例 |
cache | 緩存管理 |
class_basename | 獲取類名(不包含命名空間) |
class_uses_recursive | 獲取一個(gè)類里所有用到的trait |
config | 獲取和設(shè)置配置參數(shù) |
cookie | Cookie管理 |
download | 獲取\think\response\Download對(duì)象實(shí)例 |
dump | 瀏覽器友好的變量輸出 |
env | 獲取環(huán)境變量 |
event | 觸發(fā)事件 |
halt | 變量調(diào)試輸出并中斷執(zhí)行 |
input | 獲取輸入數(shù)據(jù) 支持默認(rèn)值和過濾 |
invoke | 調(diào)用反射執(zhí)行callable 支持依賴注入 |
json | JSON數(shù)據(jù)輸出 |
jsonp | JSONP數(shù)據(jù)輸出 |
lang | 獲取語言變量值 |
parse_name | 字符串命名風(fēng)格轉(zhuǎn)換 |
redirect | 重定向輸出 |
request | 獲取當(dāng)前Request對(duì)象 |
response | 實(shí)例化Response對(duì)象 |
session | Session管理 |
token | 生成表單令牌輸出 |
trace | 記錄日志信息 |
trait_uses_recursive | 獲取一個(gè)trait里所有引用到的trait |
url | Url生成 |
validate | 實(shí)例化驗(yàn)證器 |
view | 渲染模板輸出 |
display | 渲染內(nèi)容輸出 |
xml | XML數(shù)據(jù)輸出 |
app_path | 當(dāng)前應(yīng)用目錄 |
base_path | 應(yīng)用基礎(chǔ)目錄 |
config_path | 應(yīng)用配置目錄 |
public_path | web根目錄 |
root_path | 應(yīng)用根目錄 |
runtime_path | 應(yīng)用運(yùn)行時(shí)目錄 |
// 獲取輸入數(shù)據(jù),跟Request::param()效果一樣$param = input();
// 變量調(diào)試輸出并中斷執(zhí)行
$shop = Db::table('shop_goods')->select();
halt($shop);
// 渲染模板輸出,跟View::fetch()效果一樣
return view();
七、調(diào)試
1、調(diào)試模式 和 Trace調(diào)試
根目錄里
.env
文件
// 開啟調(diào)試模式 和 Trace調(diào)試
APP_DEBUG = true
備:正式部署后關(guān)閉調(diào)試模式
2、變量調(diào)試
ThinPHP內(nèi)置了
dump
調(diào)試方法
$shop = Db::table('shop_goods')->select();
dump($shop);