도구 태그
ThinkPHP6.0 기타
1. Session
Session클래스를 사용하려면 Facade 메소드(thinkfacadeSession)를 사용하여Session类必须使用门面方式(thinkfacadeSession)调用新版本不支持操作原生
$_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
中间件
appmiddleware.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">密 码</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类必须使用门面方式(
thinkfacadeCookie)调用配置文件位于配置目录下的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, ];
三、缓存
要使用缓存必须使用门面方式(
thinkfacadeCache)调用内置支持的缓存类型包括
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🎜을 호출해야 합니다. 버전은 기본 작업을 지원하지 않습니다< code>$_SESSION 배열과
session_으로 시작하는 모든 함수는 Session 클래스(또는 도우미 함수)를 통해서만 작동할 수 있습니다🎜 ul>🎜1. 구성 파일 세션 .php🎜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. 세션 열기🎜🎜🎜🎜미들웨어 appmiddleware.php 파일🎜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();
}
}🎜3. 🎜세션은 다중 레벨 배열 작업을 지원합니다. 🎜rrreee🎜4. 읽기 🎜rrreee🎜5. 삭제 🎜rrreee🎜6. 로그인 예제 🎜🎜🎜🎜삭제. 새로운 login.php 파일🎜rrreee🎜🎜🎜새 Login/index.html 파일🎜rrreee🎜🎜🎜index/index.html 파일🎜 rrreee🎜 2. Cookie🎜 🎜🎜🎜Cookie 클래스를 사용하려면 Facade 메소드(thinkfacadeCookie)를 사용하여 🎜🎜🎜를 호출해야 합니다. 구성 파일은 다음 위치에 있습니다. 쿠키 초기화🎜🎜1. 쿠키🎜rrreee🎜2를 사용하세요. file🎜🎜🎜🎜config 디렉터리 cookie.php file🎜rrreee🎜Three , 캐시🎜🎜🎜🎜캐시를 사용하려면 파사드 메소드(thinkfacadeCache)를 사용해야 합니다. call🎜🎜🎜기본적으로 지원되는 캐시 유형에는 file, memcache , wincache, sqlite가 포함됩니다. , redis🎜🎜1. 캐시🎜rrreee🎜2를 사용하세요. 캐시 구성 파일🎜🎜🎜🎜config 디렉토리의 캐시.php 파일🎜 rrreee🎜Four. Public Controller🎜🎜🎜🎜BaseController.php 기본 기본 컨트롤러 클래스🎜 rrreee🎜 5. Facade Facade🎜🎜🎜🎜Facade는 다음에 대한 정적 호출 인터페이스를 제공합니다. (동적) 클래스를 컨테이너에 포함합니다. 기존의 정적 메소드 호출과 비교하여 더 나은 안정성과 확장성을 제공하며 모든 비정적 클래스 라이브러리에 대해 facade 클래스를 정의할 수 있습니다.| (동적) 클래스 라이브러리 | Facade 클래스 |
| thinkApp | thinkfacadeApp |
| thinkCache | thinkfacadeCache |
| thinkConfig | thinkfacadeConfig |
| thinkCookie | thinkfacadeCookie |
| thinkDb | thinkfacadeDb |
| thinkEnv | thinkfacadeEnv |
| thinkEvent | thinkfacadeEvent |
| thinkFilesystem | thinkfacade파일 시스템 |
| thinkLang | thinkfacadeLang |
| thinkLog | thinkfacadeLog |
| thinkMiddleware | thinkfacadeMiddleware |
| thinkRequest | thinkfacadeRequest |
| thinkResponse | thinkfacadeResponse |
| thinkRoute | thinkfacadeRoute |
| thinkSession | thinkfacadeSession |
| thinkValidate | thinkfacadeValidate |
| thinkView | thinkfacadeView |
1. Facade 클래스
Facade는 컨테이너의 (동적) 클래스에 대한 정적 호출 인터페이스를 제공하여 기존 정적 메서드 호출보다 더 나은 테스트 가능성과 확장성을 제공합니다.
시스템은 대부분의 핵심 클래스 라이브러리에 대해 Facade를 정의했습니다. , Facade
2. (동적) 클래스 라이브러리
rrreee6. 도우미 함수
Thinkphp 시스템은 일반적으로 사용되는 일부에 사용됩니다. 작업 방법은 도우미 함수를 캡슐화합니다
| 도우미 기능 | 설명 |
| abort | 실행을 중단하고 HTTP 상태 코드 보내기 |
| app | 컨테이너에서 인스턴스를 빠르게 가져오기 종속성 주입 지원 |
| 바인딩 | 빠르게 바인딩 정의된 객체 인스턴스 |
| cache | cache 관리 |
| class_basename | 클래스 이름 가져오기(네임스페이스 제외) |
| class_uses_recursive | 클래스에 사용되는 모든 특성 가져오기 |
| config | 구성 매개변수 가져오기 및 설정 |
| cookie | 쿠키 관리 |
| download | Get thinkresponseDownload 개체 인스턴스 |
| dump | 브라우저 친화적인 변수 출력 |
| 환경 변수 가져오기 | |
| 트리거 이벤트 | |
| 변수 디버깅 출력 및 인터럽트 실행 | |
| 입력 데이터 가져오기는 기본값 및 필터링을 지원합니다 | |
| invoke | 호출 반사 실행 호출 가능 종속성 주입 지원 |
| json | JSON 데이터 출력 |
| jsonp | JSONP 데이터 출력 |
| lang | 언어 변수 값 가져오기 |
| parse_name | 문자열 명명 스타일 변환 |
| redirect | Redirect 출력 |
| request | 현재 요청 개체 가져오기 |
| 응답 | 응답 개체 인스턴스화 |
| ses | 세션 관리 |
| 토큰 | 양식 토큰 출력 생성 |
| trace | 로그 정보 기록 |
| trait_uses_recursive | 특성에서 참조된 모든 특성 가져오기 |
| url | Url 생성 |
| validate | 유효성 검사기 인스턴스화 |
| 보기 | 렌더링 템플릿 출력 |
| display | 렌더링 콘텐츠 출력 |
| xml | XML 데이터 출력 |
| app_path | 현재 애플리케이션 디렉토리 |
| base_path | 애플리케이션 기본 디렉토리 |
| config_path | 응용 프로그램 구성 디렉터리 |
| public_path | 웹 루트 디렉터리 |
| root_path | 응용 프로그램 루트 디렉터리 |
| runtime_path | 응용 프로그램 런타임 디렉터리 |
// 입력 데이터를 가져오고 Request::param( )는 동일한 효과를 가집니다$param = input();
// 변수 디버깅 출력 및 인터럽트 실행
$shop = Db::table('shop_goods')->select();
halt($ shop ; >.env file
// 디버깅 모드 켜기 및 디버깅 추적하기
APP_DEBUG = true
준비: 정식 배포 후 디버깅 모드 끄기- 2.
ThinPHP에는
dump디버깅 방법이 내장되어 있습니다.env文件
// 开启调试模式 和 Trace调试
APP_DEBUG = true
备:正式部署后关闭调试模式
2、变量调试
ThinPHP内置了
dump
$shop = Db::table('shop_goods')->select();dump($shop);
관련 동영상
핫 AI 도구
무료로 이미지를 벗다
사진에서 옷을 제거하는 온라인 AI 도구입니다.
사실적인 누드 사진을 만들기 위한 AI 기반 앱
더 현명한 결정을 위한 AI 기반 투자 연구
인기 기사
뜨거운 주제
20449
7
13592
4
11933
4
8937
17
8479
7
인기 있는 도구
사용하기 쉬운 무료 코드 편집기
중국어 버전, 사용하기 매우 쉽습니다.
강력한 PHP 통합 개발 환경
시각적 웹 개발 도구
신 수준의 코드 편집 소프트웨어(SublimeText3)












![PHP 실용 개발 시작하기: 빠른 PHP 생성 [중소기업 포럼]](https://img.php.cn/upload/course/000/000/035/5d27fb58823dc974.jpg)
