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() | 所有参数包括post | Array([“id”] => “001” [“type”] => “5”) |
param(‘type’) | 单个参数 | “5” |
post() | POST参数 | Array() |
session(‘name’, ‘jack’) | 设置session | - |
session() | 获取session | Array([“name”] => “jack”) |
cookie(‘key’, ‘value’) | 设置cookie | - |
cookie() | 获取cookie | Array([“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
}
}
相关文章
- 【玩转服务器】lnmp 多版本PHP安装及指定PHP CLI版本
- 【PHP释放MySQL的威力】(php释放mysql)
- PHP开启MySQL扩展的必要性(php开启mysql扩展)
- php在Linux系统上的乱码问题(phplinux乱码)
- Linux更新:升级PHP版本(linux更新php版本)
- PHP 存储数据到 MySQL 数据库(php写入mysql)
- php laravel 创建项目 500报错解决方法详解编程语言
- PHP 网页编码问题详解编程语言
- 扩展如何在PHP中开启Redis扩展(php开启redis)
- 基于PHP的Redis视频教程(redis视频教程php)
- PHP MySQL 开发构建实现功能多样的网站(php mysql 类)
- 版本Linux查看PHP服务器版本号简易指南(linux 查看 php)
- PHP读取MSSQL数据库:实现简单快捷的网页查询(php读取mssql网页)
- PHP编写的MSSQL查询:实现可能性无限(php写mssql查询)
- PHP和MSSQL实现完美兼容:简单实用又稳定(php mssql兼容性)
- phpMySQL与PHP的连接——怎么做?(mysql 如何连接)
- 使用Redis需要PHP版本满足特定要求(redis需要php版本)
- Redis实现PHP限流策略(redis限流php)
- example1.php
- 用php实现像JSP,ASP里Application那样的全局变量
- array_multisort实现PHP多维数组排序示例讲解
- php图像生成函数之间的区别分析
- PHP中使用gettext解决国际化问题的例子(i18n)
- 简单实用的PHP防注入类实例