roy404 / request
Request类提供了一种面向对象的方式与您的应用程序正在处理的当前HTTP请求进行交互,以及检索与请求一起提交的输入和文件。
1.0.2
2024-02-20 09:20 UTC
Requires
- php: ^8.0
README
使用Composer安装包
composer require roy404/request
文档
这个PHP类旨在处理HTTP请求并提供验证和错误处理功能。它扩展了Blueprints
类,并提供验证输入、访问请求数据和检查错误的方法。
用法
-
实例化类:创建
Request
类的一个实例以访问其方法。$request = new Request(); # Access request data: Use the input(), inputs(), has(), method(), only(), and except() methods to access request data. $email = $request->input('email'); $inputs = $request->inputs(); $hasEmail = $request->has('email'); $method = $request->method(); $filteredInputs = $request->only(['email', 'name']); $filteredInputs = $request->except(['password']);
-
验证输入:使用
validate()
方法指定验证规则,并使用isSuccess()
和isFailed()
方法检查验证是否成功。$request->validate([ 'email' => 'required|email', 'file' => 'required|file|extensions:xlsx,pdf|max:200', 'images' => 'required|image|dimensions:max_width=1800,max_height=1500' ]); if ($request->isSuccess()) { // Validation successful } else { // Validation failed $errors = $request->errors(); }
-
设置自定义错误消息:在
isSuccess()
和isFailed()
之前使用message()
方法设置验证规则的自定义错误消息。$request->message([ 'email' => [ 'required' => 'Email address is required.' ], 'file' => [ 'required' => 'Please upload a file.' ] ]);
可用方法
inputs(): array
:获取所有输入值。input(string $name): mixed
:获取特定输入的值。has(string $key): bool
:检查输入是否存在。method(): string
:获取HTTP请求方法。only(array $input_keys): array
:获取指定的输入值。except(array $input_keys): array
:获取所有输入值,除了指定的键。errors(bool $force_all = false): array
:获取验证错误。error(string $key): mixed
:获取特定输入键的错误消息。isMatched(string $key, mixed $value): bool
:检查输入值是否与指定值匹配。isSuccess(): bool
:检查验证是否成功。isFailed(): bool
:检查验证是否失败。validate(array $array): self
:设置验证规则。message(array $array): void
:设置自定义错误消息。
验证规则
image
:确保输入是有效的图像文件,如JPEG、PNG、GIF、SVG或WEBP。file
:验证输入是否是有效的文件上传。required
:检查输入是否为空。array
:验证输入是否为数组。null
:检查输入是否为null。numeric
:确保输入是数值。integer
:检查输入是否为整数。string
:验证输入是否为字符串。email
:验证输入是否是有效的电子邮件地址。password
:验证输入是否是有效的密码。confirmed
:检查输入值是否与另一个字段匹配(通常用于密码确认)。mimes
:指定文件上传允许的MIME类型,如JPEG、PNG、PDF等。extensions
:指定文件上传允许的文件扩展名,如pdf、xlsx等。max
:指定文件上传允许的最大文件大小(以MB为单位)或字符串的最大字符长度。min
:指定字符串的最小字符长度。dimensions
:验证图像文件的尺寸(宽度和高度),强制执行图像的最小或最大宽度和高度要求。它支持如max_width
、max_height
、min_width
、min_height
、width
和height
等选项。