一. 获取Request对象
之前我们已经说过,因为THinkPHP是一个单入口的框架,所有的请求都通过public下的index.php接受,并由该文件转发到相应的功能代码中,我们可以使用Request这个对象接受和处理请求参数。获取请求对象有以下三种方式:
namespace app\index\controller;
use think\Request;
class Index
{
public function index(Request $request)
{
//$request = request();方法一
//$request = Request::instance(); 方法二
//index(Request $request); 方法三,常用
dump($request);
}
}
值得注意的是,Request是单例模式的一个应用,只能初始化一次。
二. 利用Request对象接受和处理参数
利用Request对象可以获取各种信息,具体可以查看Request类的实现,Request类地址:/thinkphp/library/think/Request.php
namespace app\index\controller;
use think\Request;
class Index
{
public function index(Request $request)
{
# 访问:http://localhost/index/index/index/price/2.html?name=luffy&age=19
#获取URL信息
dump($request->domain()); # http://localhost
dump($request->pathinfo());# index/index/index/price/2.html
dump($request->path()); # index/index/index/price/2
dump($request->url()); # /index/index/index/price/2.html?name=luffy&age=19
dump($request->baseUrl()); # /index/index/index/price/2.html
#获取请求类型
dump($request->method()); # GET
dump($request->isGet()); # true
dump($request->isAjax()); # false
#获取请求参数
dump($request->get()); # array (size=2)'name' => string 'luffy' 'age' => string '19'
#从5.0开始,想获取pathinfo中的参数只能用param,之前可以用get,param还可以接受get和post中的参数
dump($request->param());
# array (size=2)'name' => string 'luffy' 'age' => string '19' 'price' => string '2' (length=1)
#session、cookie
session("name", "zhangjia");# 设置session
dump($request->session());# array (size=1) 'name' => string 'zhangjia' (length=8)
cookie("age", 22); # 设置cookie
dump($request->cookie());
/*
array (size=2)
'PHPSESSID' => string 'uovef2bnl9beccelovs262pkl3' (length=26)
'age' => int 22
*/
#获取模块
dump($request->module()); # index
#获取控制器
dump($request->controller()); # Index
#获取操作
dump($request->action()); # index
}
public function test()
{
return "test";
}
}
三. input助手函数
ThinkPHP框架中,助手函数都是在/thinkphp/helper.php中定义的,input函数可以更方便的获取get、 post、 put、 patch、 delete、 route、 param、 request、 session、 cookie、 server、 env、 path、 file中的参数。
namespace app\index\controller;
use think\Request;
class Index
{
public function index(Request $request)
{
dump(input("name")); # 从param()中获取key为name 的值
dump(input("post.name")); # 从param()的post请求的参数中获取key为name 的值,如果没有,输出NULL
dump(input("session.name",100)); # 如果不存在,则默认值为100
dump(input("age")); # '19'
dump(input("age/d")); # 19 #强制转换为int
# s:字符串
# d:整型
# b:布尔
# a:数组
# f:浮点
}
}
四. 响应对象Response
接下来以一个简单的例子来实现动态的设置响应格式:
namespace app\api\controller;
use think\Config;
use think\Controller;
class Index extends Controller
{
public function index($type)
{
if (!in_array($type, ['json', 'xml'])) { # 搜索$type的值是否在['json','xml']数组中
$type = 'json';
}
Config::set('default_return_type', $type);
$data = ['name' => "zhangjia"];
return $data;
}
}
参考资料