使用基类 think\Request 或者使用静态代理 think\facade\Request
1. 请求对象调用
我们通常使用依赖注入的方式完成请求对象的注入,而不用显示的创建对象。通常使用两种方式完后依赖注入,一、构造方法注入请求对象,二、操作方法注入请求对象
1.1 构造方法注入
控制器:
<?phpnamespace app\test\controller;use think\Request;class Inject{/*** 构造方法注入请求对象*/// 用来保存 think\Request 的实例protected $request;// 构造方法public function __construct(Request $req){$this->request = $req;}// 默认actionpublic function index(){// 返回请求的参数,查询字符串中 name 对应的值return $this->request->param('name');}}
postman 访问测试:
1.2 继承基类 think\Controller
直接继承于基类 think\Controller ,系统已经自动完成了请求对象的构造方法注入了,你可以直接使用$this->request属性调用当前的请求对象。注意:这里有一点需要我们特别注意,继承的是 基类Controller而不是基类Request,这一点很容易弄错。
控制器:
<?phpnamespace app\test\controller;use think\Controller;class Inject2 extends Controller{public function index(){return $this->request->method();}}
postman 测试效果:
1.3 操作方法注入
这种使用方式是最为常见的使用方式
控制器:
<?phpnamespace app\test\controller;use think\Request;class Inject3{public function index(Request $req){return $req->ip();}}
postman 测试:
2. Facade 类调用
如果不使用依赖注入和继承controller基类的方式,那么使用 Facade 静态调用也是比较常见的
控制器:
<?phpnamespace app\test\controller;use think\facade\Request;class Inject4{public function index(){return Request::url();}}
postman 测试:
3. 助手函数
使用提供的助手函数,在任何时候都可以调用到请求对象
<?phpnamespace app\test\controller;class Inject5{public function index(){return request()->method();}}
postman 测试:
