Request 请求对象
Request 对象封装了 Swoole HTTP 请求(Swoole\Http\Request),提供参数获取、请求头、Cookie、URI、上传文件等读取能力,并支持注入 RequestInterface 类型或通过静态门面(Facade)在任意位置调用。
获取 Request 实例
三种常用方式:
use Viswoole\HttpServer\Contract\RequestInterface;
use Viswoole\HttpServer\Facade\Request;
// 方式一:方法参数类型注入(容器解析,推荐)
public function info(RequestInterface $request): array
{
return ['method' => $request->getMethod()];
}
// 方式二:静态门面
$method = Request::getMethod();
// 方式三:从容器获取
$request = app(RequestInterface::class);框架的 HttpService 会将 RequestInterface、request 别名与 Request 类统一绑定到实现类;若应用定义了 \App\Request 类(继承框架 Request),绑定会自动指向自定义实现,可继承后重写 $filter 属性定制全局过滤规则。
请求参数
| 方法 | 返回值 | 说明 |
|---|---|---|
get(?string $key = null, mixed $default = null) | mixed | 获取 URL 查询参数,$key 为 null 时返回全部 |
post(?string $key = null, mixed $default = null) | mixed | 获取 POST 请求体数据,JSON 包体已自动解析 |
param(?string $key = null, mixed $default = null, array|string|null $filter = null) | mixed | 按请求方法自动取值:GET 请求走查询参数,其他走 POST;字符串值经过滤器处理 |
params(array|string|null $rule = null, bool $isShowNull = true) | array | 批量获取参数 |
addParams(array $params, string $type = 'auto') | void | 合并写入请求参数,$type 支持 get、post、auto |
// GET /search?keyword=php&page=1
Request::get('keyword'); // 'php'
Request::get('page', 1); // '1'(原始值均为字符串)
Request::get(); // ['keyword' => 'php', 'page' => '1']
// POST 请求体 {"name": "张三", "age": 18}
Request::post('name'); // '张三'
Request::post(); // 全部 POST 数据
// 按请求方法自动取值,并应用过滤器
Request::param('keyword');
Request::param('content', null, ['strip_tags']); // 在全局过滤基础上叠加 strip_tags
// 批量获取:[键名 => 默认值] 或 [键名, ...]
Request::params(['keyword' => '', 'page' => 1]);
Request::params(['keyword', 'page']); // 缺失字段值为 null
Request::params(null, false); // 获取全部参数并剔除 null 字段params() 的 rule 参数
| 取值 | 行为 |
|---|---|
null | 返回全部参数(等价 param() 不传键) |
'keyword' | 只取单个字段,结果为 ['keyword' => 值] |
['keyword', 'page'] | 取多个字段,缺失时为 null |
['keyword' => '', 'page' => 1] | 取多个字段并设置默认值 |
$isShowNull = false | 剔除值为 null 的字段 |
全局过滤规则
param() 取出的字符串值会经过全局过滤器($filter 属性)处理,默认应用 htmlspecialchars(ENT_QUOTES | ENT_SUBSTITUTE),防止 XSS(跨站脚本)攻击:
// 用户输入:<script>alert('xss')</script>
Request::param('name');
// <script>alert('xss')</script>get()、post()等方法原样返回,不经过过滤;富文本场景请使用它们或自行处理;- 第三参
$filter是在全局规则之上叠加的过滤器(字符串为单个函数名,数组键为函数名、值为额外参数),无法通过传空数组跳过全局过滤; - 修改全局过滤:继承
Viswoole\HttpServer\Request并重写protected array $filter属性,再定义\App\Request类让绑定自动切换。
请求标头
| 方法 | 返回值 | 说明 |
|---|---|---|
getHeader(?string $key = null, mixed $default = null) | array|string|null | 获取标头,键名统一小写;传 $key 返回字符串,不传返回全部 |
hasHeader(string $key) | bool | 判断标头是否存在(不区分大小写) |
setHeader(string $name, string $value) | RequestInterface | 设置(新增或覆盖)标头,支持链式调用 |
Request::getHeader('Content-Type'); // 'application/json'(键名不区分大小写)
Request::getHeader('X-Custom', ''); // 带默认值
Request::getHeader(); // 全部标头关联数组
Request::hasHeader('authorization');Header 工具类
Viswoole\HttpServer\Header 提供标头静态工具:validate($name, $value) 校验标头合法性(拦截 CRLF 注入)、formatName($name, $mode) 格式化键名大小写、formatHeaders($headers) 批量转换值类型。setHeader() 内部即调用它做安全校验。
Cookie
Request::cookie('session_id'); // 单个 Cookie,缺失返回 null
Request::cookie('token', ''); // 带默认值
Request::cookie(); // 全部 Cookie 关联数组签名:cookie(?string $key = null, mixed $default = null): mixed。
Server 信息
getServer(?string $key = null, mixed $default = null): mixed 等价于传统 PHP 的 $_SERVER:
Request::getServer('request_time_float'); // 请求开始时间戳(浮点)
Request::getServer('remote_addr'); // 客户端地址
Request::getServer('server_protocol'); // 如 'HTTP/1.1'
Request::getServer(); // 完整 server 数组请求基本信息
| 方法 | 返回值 | 说明 |
|---|---|---|
getMethod() | string | HTTP 请求方法(大写,如 GET、POST) |
ip() | string | 客户端 IP:优先取 x-real-ip 标头,回退 remote_addr,取不到为 UNKNOWN |
getPath() / target() | string | 请求路径(不含查询串),优先 path_info,回退 request_uri |
getUri() | Uri | 完整 URI 值对象 |
getProtocolVersion() | string | 协议版本,如 '1.1'、'2' |
https() | bool | 是否 HTTPS(按 Swoole Server 的 ssl 配置判断) |
isJson() | bool | Accept 标头是否期望 JSON 响应 |
getAcceptType() | string | 客户端期望的资源类型别名(json、html、xml 等,未匹配为 *) |
getBasicAuthCredentials() | array|null | 从 Authorization 标头解析 Basic 认证 [username, password] |
public function debug(): array
{
return [
'method' => Request::getMethod(),
'ip' => Request::ip(),
'path' => Request::getPath(),
'is_json' => Request::isJson(),
'https' => Request::https(),
'protocol' => Request::getProtocolVersion(),
];
}isJson() 与 getAcceptType() 依据 Request::ACCEPT_TYPE 常量中的 MIME 映射匹配(如 json 对应 application/json,text/x-json,text/json)。
URI 对象
getUri() 返回 Viswoole\HttpServer\Message\Uri——不可变的 URI 值对象,with* 系列方法返回修改后的新实例:
| 方法 | 返回值 | 说明 |
|---|---|---|
getScheme() | string | 协议方案,http 或 https |
getAuthority() | string | 授权部分(host:port,默认端口省略) |
getUserInfo() | string | 用户信息(来自 Basic 认证标头) |
getHost() | string | 主机名或 IP |
getPort() | int|null | 端口,协议默认端口为 null |
getPath() | string | 资源路径 |
getQuery() | string | 查询字符串(不含 ?) |
getFragment() | string | 片段标识(不含 #) |
__toString() | string | 完整 URI 字符串 |
$uri = Request::getUri();
$uri->getHost(); // 'example.com'
(string)$uri; // 'http://example.com/api/user?page=1'上传文件
Request::files('avatar'); // UploadedFile(单文件)
Request::files('photos'); // UploadedFile[](多文件)
Request::files(); // 全部上传文件关联数组,无文件时为 null签名:files(?string $key = null): array|UploadedFile|null。完整用法见文件上传。
原始请求内容
Request::getContent(); // 原始请求体,等价 fopen('php://input'),失败返回 false
Request::getData(); // 完整原始 HTTP 报文(含请求行与标头),HTTP/2 下不可用底层 Swoole 对象与属性代理
$swooleRequest = Request::getSwooleRequest(); // \Swoole\Http\Request
$fd = $swooleRequest->fd; // 连接文件描述符Request 实现了魔术代理:访问不存在的属性/方法时转发到底层 Swoole\Http\Request,目标不存在时抛出异常。门面只代理方法调用,需要访问 Swoole 属性(如 fd、headerSize)时请先经 getSwooleRequest() 取出底层对象。
工厂方法 create()
在非 onRequest 回调场景(如异步任务)构造请求对象:
// options 为 Swoole\Request::create 的配置项
$request = Request::create([
'parse_cookie' => true,
'parse_body' => true,
'parse_files' => true,
]);相关阅读
- Response 响应对象:响应输出与状态码控制
- 自动注入注解:优先使用注解注入,减少手动取值
- Facade 门面:静态代理的实现原理
