企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# ThinkPHP6 交互 --- ## 一、`ThinkPHP6` 容器和依赖注入 * 支持使用依赖注入的场景 > 控制器架构方法 > 控制器操作方法 > 路由的闭包定义 > 事件类的执行方法 > 中间件的执行方法 ## 二、`ThinkPHP6` 门面 `Facade` * 门面为容器中的(动态)类提供了一个静态调用接口,相比于传统的静态方法调用, 带来了更好的可测试性和扩展性,你可以为任何的非静态类库定义一个 `facade` 类。 * 系统已经为大部分核心类库定义了 `Facade` ,所以你可以通过 `Facade` 来访问这些系统类,当然也可以为你的应用类库添加静态代理。 ## 三、容器和依赖注入、门面 **系统类库**|**容器绑定标识**|**Facade类** ---|---|--- think\\App|app|think\\facade\\App think\Cache|cache|think\facade\Cache think\Config|config|think\facade\Config think\Cookie|cookie|think\facade\Cookie think\Console|console| think\Db|db|think\facade\Db think\Debug|debug| think\Env|env|think\facade\Env think\Event|event|think\facade\Event think\Http|http| think\Lang|lang|think\facade\Lang think\Log|log|think\facade\Log think\Middleware|middleware|think\facade\Middleware think\Request|request|think\facade\Request think\Response|response|think\facade\Response think\Route|route|think\facade\Route think\Session|session|think\facade\Session think\Validate|validate|think\facade\Validate think\View|view|think\facade\View ## 三、案例 > 1、实现前端代码 ``` <!DOCTYPE html> <html> <head> <title>管理系统</title> <link rel="stylesheet" href="/static/layui/css/layui.css"> </head> <body style="padding:30px;"> <table> <thead> <tr> <th>ID</th> <th>手机号</th> <th>昵称</th> <th>性别</th> <th>头像</th> <th>状态</th> <th>最后登录时间</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </body> </html> ``` > 2、代码交互 ```php // php代码 namespace app\index\controller; use think\View; use think\facade\Db; class Index { public function index(View $view){ $user = Db::table('user')->select(); $view->assign([ 'user' => $user ]); return $view->fetch(); } } ``` ```html <!DOCTYPE html> <html> <head> <title>管理系统</title> <link rel="stylesheet" href="/static/layui/css/layui.css"> </head> <body style="padding:30px;"> <table> <thead> <tr> <th>ID</th> <th>手机号</th> <th>昵称</th> <th>性别</th> <th>头像</th> <th>状态</th> <th>最后登录时间</th> </tr> </thead> <tbody> {foreach $user as $v} <tr> <td>{$v['uid']}</td> <td>{$v['phone']}</td> <td>{$v['nickname']}</td> <td>{$v['sex']}</td> <td>{$v['avatar']}</td> <td>{$v['status']}</td> <td>{$v['last_time']}</td> </tr> {/foreach} </tbody> </table> </body> </html> ``` ## 四、请求 * 请求对象由 `think\Request` 类负责 > 获取当前请求信息方法 **方法**|**功能** ---|--- host|当前访问域名或者IP scheme|当前访问协议 port|当前访问的端口 remotePort|当前请求的REMOTE_PORT protocol|当前请求的SERVER_PROTOCOL contentType|当前请求的CONTENT_TYPE domain|当前包含协议的域名 subDomain|当前访问的子域名 panDomain|当前访问的泛域名 rootDomain|当前访问的根域名 url|当前完整URL baseUrl|当前URL(不含QUERY_STRING) query|当前请求的QUERY_STRING参数 baseFile|当前执行的文件 root|URL访问根地址 rootUrl|URL访问根目录 pathinfo|当前请求URL的pathinfo信息(含URL后缀) ext|当前URL的访问后缀 time|获取当前请求的时间 type|当前请求的资源类型 method|当前请求类型 rule|当前请求的路由对象实例 ```php // php代码 namespace app\index\controller; use think\facade\Request; class Index { public function index(){ print_r(Request::host().'<br/>'); print_r(Request::scheme().'<br/>'); print_r(Request::port().'<br/>'); print_r(Request::domain().'<br/>'); } } ``` > 获取参数方法 **方法**|**功能** ---|--- param|获取当前请求的变量 get|获取 $_GET 变量 post|获取 $_POST 变量 file|获取 $_FILES 变量 put|获取 PUT 变量 delete|获取 DELETE 变量 session|获取 $_SESSION 变量 cookie|获取 $_COOKIE 变量 request|获取 $_REQUEST 变量 server|获取 $_SERVER 变量 env|获取 $_ENV 变量 route|获取 路由(包括PATHINFO) 变量 middleware|获取 中间件赋值/传递的变量 ```php // php代码 namespace app\admin\controller; use think\Request; class Index{ // 在index方法引入Request public function index(Request $request){ // parma 表示接收所有传过来的参数 不管是post请求还是get请求 parma都能接收到参数 $data = $request->param(); // post表示只接收 post方式传出来的参数 $data1= $request->post(); // get表示只接收get方式传出来的参数 $data2= $request->get(); // 假如你只想拿到一个id值,这时我们可以在括号里面加上id即可。 $data = $request->param('id'); } } ``` > 判断请求类型 **方法**|**功能** ---|--- method|获取当前请求类型 isGet|判断是否GET请求 isPost|判断是否POST请求 isPut|判断是否PUT请求 isDelete|判断是否DELETE请求 isAjax|判断是否AJAX请求 isPjax|判断是否PJAX请求 isJson|判断是否JSON请求 isMobile|判断是否手机访问 isHead|判断是否HEAD请求 isPatch|判断是否PATCH请求 isOptions|判断是否OPTIONS请求 isCli|判断是否为CLI执行 isCgi|判断是否为CGI模式 ```php // php代码 namespace app\index\controller; use think\facade\Request; class Index { public function index(){ var_dump(Request::method()); var_dump(Request::isGet()); var_dump(Request::isPost()); } } ``` > 获取HTTP头信息 **方法**|**功能** ---|--- header|获取当前请求的HTTP请求头信息 ```php // php代码 namespace app\index\controller; use think\facade\Request; class Index { public function index(){ $info = Request::header(); var_dump($info); } } ``` ## 五、上传 * 内置的上传只是上传到本地服务器,上传到远程或者第三方平台的话需要安装额外的扩展 > 单图上传 ```php // php代码 namespace app\index\controller; use think\facade\View; use think\facade\Db; use think\facade\Request; class Index { public function index(){ return View::fetch(); } public function upload(){ # image 是input的name $file = Request::file('image'); if($file==null){ exit(json_encode(array('code'=>1,'msg'=>'没有文件上传'))); } $info = $file->validate(['ext'=>'jpg,png,gif,jpeg'])->move('./uploads'); if(empty($info)){ exit(json_encode(array('code'=>1,'msg'=>$file->getError()))); } $img = '/uploads/'.$info->getSaveName(); exit(json_encode(array('code'=>0,'data'=>$img))); } } ``` ```html <!DOCTYPE html> <html> <head> <title>上传</title> </head> <body> <form action="index.php/index/index/upload" enctype="multipart/form-data" method="post"> <input type="file" name="image" /> <br> <input type="submit" value="上传" /> </form> </body> </html> ``` > 多图上传 ```php // php代码 namespace app\index\controller; use think\facade\View; use think\facade\Db; use think\facade\Request; class Index { public function index(){ return View::fetch(); } public function upload(){ # image 是input的name $file = Request::file('image'); if($file==null){ exit(json_encode(array('code'=>1,'msg'=>'没有文件上传'))); } foreach($file as $file_v){ $info = $file_v->validate(['ext'=>'jpg,png,gif,jpeg'])->move('./uploads'); if(empty($info)){ exit(json_encode(array('code'=>1,'msg'=>$file_v->getError()))); } $img[] = '/uploads/'.$info->getSaveName(); } exit(json_encode(array('code'=>0,'data'=>$img))); } } ``` ```html <!DOCTYPE html> <html> <head> <title>上传</title> </head> <body> <form action="index.php/index/index/upload" enctype="multipart/form-data" method="post"> <input type="file" name="image" /><br> <input type="file" name="image[]" /><br> <input type="file" name="image[]" /><br> <input type="submit" value="上传" /> </form> </body> </html> ``` ## 六、后台管理案例 * 前端框架使用layui > php代码 ```php namespace app\index\controller; use think\facade\View; use think\facade\Db; use think\facade\Request; class User { public function index(){ $get = Request::get(); if(isset($get['wd'])){ if($get['select'] == 'phone'){ $where[] = ['phone','like','%'.$get['wd'].'%']; }else{ $where[] = ['u_name','like','%'.$get['wd'].'%']; } }else{ $where = true; } $user = Db::table('user')->where($where)->paginate([ 'list_rows' => 5, 'query' => request()->param() ]); View::assign([ 'user' => $user ]); return View::fetch(); } public function add(){ if(Request::isPost()){ $post = Request::post(); $post['last_time'] = time(); $add = Db::table('user')->insert($post); if($add){ exit(json_encode(array('code'=>0,'msg'=>'添加成功'))); }else{ exit(json_encode(array('code'=>1,'msg'=>'添加失败'))); } }else{ return View::fetch(); } } public function edit(){ if(Request::isPost()){ $uid = Request::post('uid'); $post = Request::post(); $post['last_time'] = time(); $edit = Db::table('user')->where('uid',$uid)->update($post); if($edit){ exit(json_encode(array('code'=>0,'msg'=>'修改成功'))); }else{ exit(json_encode(array('code'=>1,'msg'=>'修改失败'))); } }else{ $uid = Request::get('uid'); $user = Db::table('user')->where('uid',$uid)->find(); View::assign([ 'user' => $user ]); return View::fetch(); } } public function delete(){ $uid = Request::post('uid'); $delete = Db::table('user')->where('uid',$uid)->delete(); if($delete){ exit(json_encode(array('code'=>0,'msg'=>'删除成功'))); }else{ exit(json_encode(array('code'=>1,'msg'=>'删除失败'))); } } } ``` > 数据列表页 ```html <!DOCTYPE html> <html> <head> <title>后台管理系统</title> <link rel="stylesheet" href="/static/layui/css/layui.css"> <script src="/static/layui/layui.js"></script> <style type="text/css"> .pagination { display: inline-block; padding-left: 0; margin: 20px 0; border-radius: 4px; } .pagination > li { display: inline; } .pagination > li > a, .pagination > li > span { position: relative; float: left; padding: 6px 12px; margin-left: -1px; line-height: 1.42857143; color: #337ab7; text-decoration: none; background-color: #fff; border: 1px solid #ddd; } .pagination > li:first-child > a, .pagination > li:first-child > span { margin-left: 0; border-top-left-radius: 4px; border-bottom-left-radius: 4px; } .pagination > li:last-child > a, .pagination > li:last-child > span { border-top-right-radius: 4px; border-bottom-right-radius: 4px; } .pagination > li > a:hover, .pagination > li > span:hover, .pagination > li > a:focus, .pagination > li > span:focus { z-index: 2; color: #23527c; background-color: #eee; border-color: #ddd; } .pagination > .active > a, .pagination > .active > span, .pagination > .active > a:hover, .pagination > .active > span:hover, .pagination > .active > a:focus, .pagination > .active > span:focus { z-index: 3; color: #fff; cursor: default; background-color: #337ab7; border-color: #337ab7; } .pagination > .disabled > span, .pagination > .disabled > span:hover, .pagination > .disabled > span:focus, .pagination > .disabled > a, .pagination > .disabled > a:hover, .pagination > .disabled > a:focus { color: #777; cursor: not-allowed; background-color: #fff; border-color: #ddd; } </style> </head> <body style="padding:30px;"> <div style="margin-top:10px;" class="layui-form"> <div class="layui-form-item layui-form-pane" style="width:800px;"> <div class="layui-input-inline"> <select id="select" lay-filter="aihao"> <option value="phone" {if $select=='phone'?'selected':''}>手机号</option> <option value="u_name" {if $select=='u_name'?'selected':''}>姓名</option> </select> </div> <input type="text" class="layui-input" style="display:inline-block;width:150px;" id="wd" value="{$wd}" placeholder="输入关键词"> <button class="layui-btn" onclick="searchs()"><i class="layui-icon">&#xe615;</i>搜索</button> </div> </div> <button class="layui-btn" onclick="add()">添加</button> <table class="layui-table"> <thead> <tr> <th>ID</th> <th>手机号</th> <th>昵称</th> <th>性别</th> <th>头像</th> <th>状态</th> <th>最后登录时间</th> <th>操作</th> </tr> </thead> <tbody> {foreach $user as $v} <tr> <td>{$v['uid']}</td> <td>{$v['phone']}</td> <td>{$v['nickname']}</td> <td>{$v['sex']}</td> <td>{$v['avatar']}</td> <td>{$v['status']}</td> <td>{$v['last_time']}</td> <td> <button class="layui-btn layui-btn-xs" onclick="edit({$v['uid']})">编辑</button> <button class="layui-btn layui-btn-danger layui-btn-xs" onclick="del({$v['uid']})">删除</button> </td> </tr> {/foreach} </tbody> </table> {$user|raw} </body> </html> <script type="text/javascript"> layui.use(['laypage','layer','form'], function(){ var laypage = layui.laypage; layer = layui.layer; $ = layui.jquery; var form = layui.form; }); // 添加、编辑 function add(){ layer.open({ type: 2, title: '添加', shade: 0.3, area: ['480px', '450px'], content:'/index.php/index/User/add' }); } // 编辑 function edit(uid){ layer.open({ type: 2, title: '添加', shade: 0.3, area: ['480px', '450px'], content:'/index.php/index/User/edit?uid='+uid }); } // 删除 function del(uid){ layer.confirm('确定要删除吗?', { btn: ['确定','取消'] }, function(){ $.post('/index.php/index/User/del',{'uid':uid},function(res){ if(res.code>0){ layer.alert(res.msg,{icon:2}); }else{ layer.msg(res.msg); location.reload(); } },'json'); }); } // 搜索 function searchs(page){ var wd = $.trim($('#wd').val()); var select = $.trim($('#select').val()); var url = '/index.php/index/User/index?'; if(wd){ url += '&wd='+wd; } if(select){ url += '&select='+select; } window.location.href = url; } </script> ``` > 添加数据页 ```html <!DOCTYPE html> <html> <head> <title>添加</title> <link rel="stylesheet" href="/static/layui/css/layui.css"> <script src="/static/layui/layui.js"></script> </head> <body style="padding:10px;"> <form class="layui-form"> <div class="layui-form-item"> <label class="layui-form-label">手机号</label> <div class="layui-input-inline"> <input type="text" class="layui-input" name="phone" value=""> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">昵称</label> <div class="layui-input-inline"> <input type="text" class="layui-input" name="nickname" value=""> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">头像</label> <div class="layui-upload"> <button type="button" class="layui-btn" id="test1">上传图片</button> <div class="layui-upload-list"> <label class="layui-form-label">图片预览</label> <img class="layui-upload-img" style="widht:50px;height:50px;" id="img"> <input type="hidden" id="avatar" name="avatar" value=""> </div> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">性别</label> <div class="layui-input-inline"> <select name="sex" lay-filter="aihao"> <option value=""></option> <option value="0">保密</option> <option value="1">男</option> <option value="2">女</option> </select> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">状态</label> <div class="layui-input-inline"> <select name="status" lay-filter="aihao"> <option value=""></option> <option value="1">开启</option> <option value="0">关闭</option> </select> </div> </div> </form> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" onclick="save()">提交</button> </div> </div> <script type="text/javascript"> layui.use(['form','layer','upload'],function(){ var layer = layui.layer; $ = layui.jquery; var form = layui.form; var upload = layui.upload; var uploadInst = upload.render({ elem: '#test1', url: "/index.php/index/index/upload", before: function(obj){ obj.preview(function(index, file, result){ $("#img").attr("src", result); }); }, done: function(res){ if(res.code > 0){ return layer.msg("上传失败,"+res.msg); }else{ $("#avatar").val(res.data); } } }); }); function save(){ $.post('/index.php/index/User/add',$('form').serialize(),function(res){ if(res.code>0){ layer.alert(res.msg,{icon:2}); }else{ layer.msg(res.msg); setTimeout(function(){parent.window.location.reload();},1000); } },'json'); } </script> </body> </html> ``` > 数据修改页 ```html <!DOCTYPE html> <html> <head> <title>修改</title> <link rel="stylesheet" href="/static/layui/css/layui.css"> <script src="/static/layui/layui.js"></script> </head> <body style="padding:10px;"> <form class="layui-form"> <input type="hidden" name="uid" value="{$user['uid']}"> <div class="layui-form-item"> <label class="layui-form-label">手机号</label> <div class="layui-input-inline"> <input type="text" class="layui-input" name="phone" value="{$user['phone']}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">昵称</label> <div class="layui-input-inline"> <input type="text" class="layui-input" name="nickname" value="{$user['nickname']}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">头像</label> <div class="layui-upload"> <button type="button" class="layui-btn" id="test1">上传图片</button> <div class="layui-upload-list"> <label class="layui-form-label">图片预览</label> <img class="layui-upload-img" style="widht:50px;height:50px;" src="{$user['avatar']}" id="img"> <input type="hidden" id="avatar" name="avatar" value="{$user['avatar']}"> </div> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">年龄</label> <div class="layui-input-inline"> <input type="text" class="layui-input" name="age" value="{$user['age']}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">性别</label> <div class="layui-input-inline"> <select name="sex" lay-filter="aihao"> <option value=""></option> <option value="0" {$user['sex']==0?'selected':''}>保密</option> <option value="1" {$user['sex']==1?'selected':''}>男</option> <option value="2" {$user['sex']==2?'selected':''}>女</option> </select> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">状态</label> <div class="layui-input-inline"> <select name="status" lay-filter="aihao"> <option value=""></option> <option value="1" {$user['status']==1?'selected':''}>开启</option> <option value="0" {$user['status']==0?'selected':''}>关闭</option> </select> </div> </div> </form> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" onclick="save()">提交</button> </div> </div> <script type="text/javascript"> layui.use(['form','layer','upload'],function(){ var layer = layui.layer; $ = layui.jquery; var form = layui.form; var upload = layui.upload; var uploadInst = upload.render({ elem: '#test1', url: "/index.php/index/index/upload", before: function(obj){ obj.preview(function(index, file, result){ $("#img").attr("src", result); }); }, done: function(res){ if(res.code > 0){ return layer.msg("上传失败,"+res.msg); }else{ $("#avatar").val(res.data); } } }); }); function save(){ $.post('/index.php/index/User/edit',$('form').serialize(),function(res){ if(res.code>0){ layer.alert(res.msg,{icon:2}); }else{ layer.msg(res.msg); setTimeout(function(){parent.window.location.reload();},1000); } },'json'); } </script> </body> </html> ```