ThinkPHP6.0 杂项

收藏416

阅读188076

更新时间2022-04-28

前言:

ThinkPHP6.0 杂项

一、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 )调用

  • 内置支持的缓存类型包括filememcachewincachesqliteredis

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\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类

  • 门面为容器中的(动态)类提供了一个静态调用接口,相比于传统的静态方法调用,带来了更好的可测试性和扩展性

  • 系统已经为大部分核心类库定义了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  中断执行并发送HTTP状态码
app  快速获取容器中的实例 支持依赖注入
bind  快速绑定对象实例
cache  缓存管理
class_basename  获取类名(不包含命名空间)
class_uses_recursive  获取一个类里所有用到的trait
config 获取和设置配置参数
cookie  Cookie管理
download  获取\think\response\Download对象实例
dump  浏览器友好的变量输出
env  获取环境变量
event  触发事件
halt  变量调试输出并中断执行
input  获取输入数据 支持默认值和过滤
invoke  调用反射执行callable 支持依赖注入
json  JSON数据输出
jsonp JSONP数据输出
lang  获取语言变量值
parse_name  字符串命名风格转换
redirect  重定向输出
request  获取当前Request对象
response  实例化Response对象
session  Session管理
token  生成表单令牌输出
trace  记录日志信息
trait_uses_recursive  获取一个trait里所有引用到的trait
url  Url生成
validate  实例化验证器
view  渲染模板输出
display  渲染内容输出
xml  XML数据输出
app_path  当前应用目录
base_path  应用基础目录
config_path  应用配置目录
public_path  web根目录
root_path  应用根目录
runtime_path  应用运行时目录



// 获取输入数据,跟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);

科技资讯

更多

精选课程

更多
前端入门_HTML5
前端入门_HTML5

共29课时

62万人学习

CSS视频教程-玉女心经版
CSS视频教程-玉女心经版

共25课时

39.5万人学习

JavaScript极速入门_玉女心经系列
JavaScript极速入门_玉女心经系列

共43课时

71.3万人学习

独孤九贱(1)_HTML5视频教程
独孤九贱(1)_HTML5视频教程

共25课时

61.9万人学习

独孤九贱(2)_CSS视频教程
独孤九贱(2)_CSS视频教程

共22课时

23.1万人学习

独孤九贱(3)_JavaScript视频教程
独孤九贱(3)_JavaScript视频教程

共28课时

34.1万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时

125.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号