ThinkPHP6.0 Miscellaneous


1. Session

  • To use the Session class, you must use the facade method (think\facade\Session ) Calling

  • The new version does not support operating the native $_SESSION array and all functions starting with session_. It can only be called through the Session class (or assistant Function) to operate

1. Configuration file 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. Open Session

  • Middlewareapp\middleware.php File

\think\middleware\SessionInit::class

3. Settings

  • session supports multi-level array operations

Session::set('name','欧阳克');
// Session数组
Session::set('admin.name','欧阳克');
Session::set('admin.uid',1);

4. Read

// 获取全部Session
Session::all();
// 获取Session中name的值
Session::get('name');

5. Delete

Session::delete('name');

6. Get the value and delete

Session::pull('name');

7. Login example

  • New login.php file

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();
        }
    }
}
  • New Login/index.html file

<!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 file

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();
}

2. Cookie

  • To use the Cookie class, you must use the facade method ( think\facade\Cookie) Call the

  • # configuration file located in the cookie.php file in the configuration directory. No manual initialization is required. The system will automatically initialize Cookie before calling. Work

1. Using Cookie

// 设置Cookie 有效期为 3600秒
Cookie::set('name', '欧阳克', 3600);
// 永久保存Cookie
Cookie::forever('name', '欧阳克');
//删除cookie
Cookie::delete('name');
// 读取某个cookie数据
Cookie::get('name');

2. Cookie configuration file

  • cookie.php file in the config directory

return [
    // cookie 保存时间
    'expire'    => 0,
    // cookie 保存路径
    'path'      => '/',
    // cookie 有效域名
    'domain'    => '',
    //  cookie 启用安全传输
    'secure'    => false,
    // httponly设置
    'httponly'  => false,
    // 是否使用 setcookie
    'setcookie' => true,
];

3. Cache

  • To use the cache, you must use the facade method (think\facade\Cache) to call

  • Built-in supported cache types include file, memcache, wincache, sqlite, redis

1. Use cache

// 缓存在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. Cache configuration file

  • config directory cache.php File

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',
        ],
        // 更多的缓存连接
    ],
];

4. Public Controller

  • BaseController.php Default base controller class

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();
    }
}

5. Facade

  • The facade provides a static calling interface for (dynamic) classes in the container. Compared with traditional static method calling, it has For better testability and extensibility, you can define a facadeclass

    for any non-static class library
(动态)类库Facade类
think\Appthink\facade\App
think\Cachethink\facade\Cache
think\Configthink\facade\Config
think\Cookiethink\facade\Cookie
think\Dbthink\facade\Db
think\Env think\facade\Env
think\Eventthink\facade\Event
think\Filesystemthink\facade\Filesystem
think\Lang think\facade\Lang
think\Log think\facade\Log
think\Middlewarethink\facade\Middleware
think\Requestthink\facade\Request
think\Responsethink\facade\Response
think\Routethink\facade\Route
think\Sessionthink\facade\Session
think\Validatethink\facade\Validate
think\View think\facade\View

1. Facade class

  • The facade provides a static calling interface for (dynamic) classes in the container. Compared with traditional static method calling, it brings better Testability and scalability

  • The system has defined Facade for most core class libraries, so you can access these system classes through 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. (Dynamic) Class Library

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();
    }
}

6. Assistant Function

  • Thinkphp system encapsulates the assistant function for some common operation methods

##redirect Redirect outputrequest Get the current Request objectresponse Instantiate the Response objectsession Session management token Generate form token outputtrace Record log informationtrait_uses_recursive Get all the traits referenced in a traiturl Url generationvalidate Instantiated validatorview Rendering template output
Assistant functionDescription
abort Abort execution and send HTTP status code
app Quickly obtain the instance in the container supports dependency injection
bind Fast binding object instance
cache Cache management
class_basename Get the class name (not Contains namespace)
class_uses_recursive Get all traits used in a class
configGet and set configuration parameters
cookie Cookie management
download Get\think\ response\Download object instance
dump Browser-friendly variable output
env Get Environment variables
event Trigger event
halt Variable debug output and interrupt execution
input Getting input data supports default value and filtering
invoke Calling reflection execution callable supports dependency injection
json JSON data output
jsonpJSONP data output
lang Get language variable value
parse_name String naming style conversion
display Rendering content output
xml XML data output
app_path Current application directory
base_path Application base directory
config_path Application configuration directory
public_path web root directory
root_path Application root directory
runtime_path Application runtime directory


# #// Get input data, same effect as Request::param()

$param = input();

// Variable debugging output and interrupt execution

$ shop = Db::table('shop_goods')->select();

halt($shop);

// Rendering template output, with View::fetch() effect Same

return view();

7. Debugging

1. Debug mode and Trace debugging

    ##root
  • .env

    file in the directory

// Turn on debug mode and Trace debugging

APP_DEBUG = true

Preparation: Turn off debugging mode after formal deployment

2. Variable debugging

    ThinPHP has built-in
  • dump

    Debugging method

$shop = Db::table('shop_goods')->select();

dump($shop);