PHP:ThinkPHP5.0请求对象和响应对象

简介: PHP:ThinkPHP5.0请求对象和响应对象

1、Request请求对象

(1)获取Request

获取方式一:助手函数


$request = request();

获取方式二:获取实例(单例模式))


use think\Request;
$request = Request::instance();

获取方式三:注入到方法(推荐)


use think\Request;
public function requestInfo(Request $request)
    {
        $request;
    }

(2)Request方法

请求路径


GET http://127.0.0.1:8009/index/index/requestinfo/type/5.html?id=001

image.png

(3)助手函数input

input('get.id')
// 相当于
$request->get('id')
// $request->参数类型(key名,key值,函数名);
$request->get('key','value','intval');

2、响应对象Response

方式一:通过配置文件修改响应格式(整个模块生效 )

conf/api/config.php
return [
    'default_return_type'=>'json'
];

方式二:动态修改返回类型


<?php
namespace app\api\controller;
use  think\Config;
class Index
{
    public function getUserInfo($type='json')
    {
        if(!in_array($type, ['json', 'jsonp', 'xml']))
        {
            $type = 'json';
        }
        Config::set('default_return_type', $type);
        $data = [
          'code' => 200,
            'list' => [
                'name'=> 'Tom',
                'age'=>23
            ]
        ];
        return $data;
    }
}

访问:

http://127.0.0.1:8009/api/index/getuserinfo?type=json


返回


{
    code: 200,
    list: {
        name: "Tom",
        age: 23
    }
}

相关文章
|
1月前
|
Java 程序员 PHP
PHP对象和类
PHP对象和类
19 0
|
6月前
|
SQL 安全 PHP
理解php对象注入
php对象注入是一个非常常见的漏洞,这个类型的漏洞虽然有些难以利用,但仍旧非常危险,为了理解这个漏洞,请读者具备基础的php知识。
php案例:自己写个数组转换成对象 对象转换成数组的的功能出来吧
php案例:自己写个数组转换成对象 对象转换成数组的的功能出来吧
php案例:自己写个数组转换成对象 对象转换成数组的的功能出来吧
|
3月前
|
JSON PHP 数据格式
|
9月前
|
存储 JSON PHP
在 PHP 中从 URL 获取 JSON 对象
在 PHP 中从 URL 获取 JSON 对象
|
4月前
|
前端开发 PHP
【PHP学习】—get请求传递参数(五)
【PHP学习】—get请求传递参数(五)
|
7月前
|
Ubuntu PHP Windows
在安装PHP时出现了冲突请求的问题
在安装PHP时出现了冲突请求的问题
81 1
|
8月前
|
JSON PHP 数据格式
PHP - Laravel 接口请求返回 JSON 数据
PHP - Laravel 接口请求返回 JSON 数据
150 0
|
9月前
|
JSON PHP 数据格式
php清洗数据实战案例(2):根据键值进行二维数据的对象数组的排序
php清洗数据实战案例(2):根据键值进行二维数据的对象数组的排序
55 0
|
9月前
|
定位技术 PHP
php基于百度地图封装的对象类实现计算地图上两点间的距离和地理编码
php基于百度地图封装的对象类实现计算地图上两点间的距离和地理编码
60 0