文章目录
- 环境
- 在Controller中获取Request对象
- 构造器注入
- 操作方法注入
- 继承BaseController
- 助手函数
- Facade
- 参考
环境
- Windows 11 专业版
- XAMPP 8.2.12
- PHP 8.2.12
- VSCode 1.103.0
在Controller中获取Request对象
要想在Controller中获取Request对象,有以下几种方式:
- 构造器注入
- 操作方法注入
- 继承BaseController
- 助手函数
- Facade
下面一一举例说明。
构造器注入
顾名思义,在控制器的构造器里注入Request对象:
namespace app\controller;use think\Request;class Test1 {protected $request;public function __construct(Request $request) {$this->request = $request;}public function foo() {// 使用request对象echo $this->request->pathinfo();}
}
运行结果如下:
注:如果用 curl
命令访问,如果输出非常多的信息:
PS C:\> curl.exe --silent -XGET "http://localhost:8000/test1/foo"
test1/foo<style>#think_page_trace {position:fixed; bottom:0; right:0; font-size:14px; width:100%; z-index:999999; color:#000; text-align:left; font-family:'微软雅黑';}#think_page_trace_tab {display:none; background:white; margin:0; height: 250px;}#think_page_trace_tab_tit {height:30px; padding: 6px 12px 0; border-bottom:1px solid #ececec; border-top:1px solid #ececec; font-size:16px;}#think_page_trace_tab_tit>span {color:#000; padding-right:12px; height:30px; line-height:30px; display:inline-block; margin-right:3px; cursor:pointer; font-weight:700;}#think_page_trace_tab_cont {overflow:auto; height:212px; padding:0; line-height:24px;}
......
......
这是因为开启了debug模式。其实刚才页面访问时,在debug模式下,也返回了同样多的内容。注意上图中,在页面右下角有一个图标,可以点开,查看debug详细信息。
如果想要关闭debug信息,打开项目根目录里的 .env
文件:
APP_DEBUG = false
其默认值是true,改为false即可。
操作方法注入
顾名思义,在控制器的某个方法里注入Request对象:
namespace app\controller;use think\Request;class Test2 {public function foo(Request $request) {echo $request->pathinfo();}
}
运行结果如下:
PS C:\> curl.exe http://localhost:8000/test2/foo
test2/foo
这种方式好像有点怪,因为操作方法本身可以带参数,现在把request对象也放进来,感觉有点乱。
继承BaseController
namespace app\controller;use app\BaseController;class Test3 extends BaseController {public function foo() {echo $this->request->pathinfo();}
}
运行结果如下:
PS C:\> curl.exe http://localhost:8000/test3/foo
test3/foo
这种方法比较好。正常情况下,控制器就应该继承BaseController类,而BaseController类已经通过构造器注入了App对象:
abstract class BaseController {......protected $request;......public function __construct(App $app) {......$this->request = $this->app->request;......
这样,在子类控制器中,就可以直接使用request对象了。
助手函数
为了方便使用,系统为一些常用的操作方法封装了助手函数,比如:
app()
config()
dump()
json()
request()
response()
- …
其中 request()
助手函数是获取当前Request对象,可以在任何需要的时候直接调用。
namespace app\controller;class Test4 {public function foo() {echo request()->pathinfo();}
}
运行结果如下:
PS C:\> curl.exe http://localhost:8000/test4/foo
test4/foo
Facade
可以通过Facade机制来静态调用请求对象的方法:
namespace app\controller;use think\facade\Request;class Test5 {public function foo() {echo Request::pathinfo();}
}
运行结果如下:
PS C:\> curl.exe http://localhost:8000/test5/foo
test5/foo
注意区分:本例中 use
所引入的Request类和前面的有所不同。
参考
https://doc.thinkphp.cn/v8_0/request.html