zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

2023-09-14 09:07:19 时间

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

函数说明结果
domain()域名http://127.0.0.1:8009
pathinfo()路径带后缀index/index/requestinfo/type/5.html
path()路径不带后缀index/index/requestinfo/type/5
method()请求类型GET
isGet()是否为GET请求true
isPost()是否为POST请求false
isAjax()是否为ajax请求false
get()查询参数Array([“id”] => “001”)
get(“id”)查询参数“001”
param()所有参数包括postArray([“id”] => “001” [“type”] => “5”)
param(‘type’)单个参数“5”
post()POST参数Array()
session(‘name’, ‘jack’)设置session-
session()获取sessionArray([“name”] => “jack”)
cookie(‘key’, ‘value’)设置cookie-
cookie()获取cookieArray([“PHPSESSID”] => “734672fc1386d54105273362df904750” [“key”] => “value”)
module()模块index
controller()控制器Index
action()操作requestinfo
url()url带查询字符串/index/index/requestinfo/type/5.html?id=001
baseUrl()不带查询字符串/index/index/requestinfo/type/5.html

(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
    }
}