【ThinkPHP】5.1 完全开发手册 / 请求对象

请求对象

当前的请求对象由think\Request类负责,在很多场合下并不需要实例化调用,通常使用依赖注入即可。在其它场合(例如模板输出等)则可以使用think\facade\Request静态类操作。

[TOC=2,3]

请求对象调用

在控制器中通常情况下有两种方式进行依赖注入。

构造方法注入

<?php

namespace app\index\controller;

use think\Request;

class Index 
{
/**
* @var \think\Request Request实例
*/
protected $request;

/**
* 构造方法
* @param Request $request Request对象
* @access public
*/
public function __construct(Request $request)
{
$this->request = $request;
}

public function index()
{
return $this->request->param('name');
}    
}

如果你继承了系统的控制器基类think\Controller的话,系统已经自动完成了请求对象的构造方法注入了,你可以直接使用$this->request属性调用当前的请求对象。

<?php

namespace app\index\controller;

use think\Controller;

class Index extends Controller
{

public function index()
{
return $this->request->param('name');
}    
}

操作方法注入

另外一种选择是在每个方法中使用依赖注入。

<?php

namespace app\index\controller;

use think\Controller;
use think\Request;

class Index extends Controller
{

public function index(Request $request)
{
return $request->param('name');
}    
}

无论是否继承系统的控制器基类,都可以使用操作方法注入。

更多关于依赖注入的内容,请参考后续的依赖注入章节。

Facade调用

在没有使用依赖注入的场合,可以通过Facade机制来静态调用请求对象的方法(注意use引入的类库区别)。

<?php

namespace app\index\controller;

use think\Controller;
use think\facade\Request;

class Index extends Controller
{

public function index()
{
return Request::param('name');
}    
}

该方法也同样适用于依赖注入无法使用的场合。

助手函数

为了简化调用,系统还提供了request助手函数,可以在任何需要的时候直接调用当前请求对象。

<?php

namespace app\index\controller;

use think\Controller;

class Index extends Controller
{

public function index()
{
return request()->param('name');
}
}