synortix / laravel-dictionary
Laravel API 字典支持和验证库。在API资源响应中人性化你的枚举。
1.0.1
2019-10-07 09:32 UTC
Requires
- php: ^7.0
- laravel/framework: >=5.0
- myclabs/php-enum: ^1.6
Requires (Dev)
- phpunit/phpunit: ^7
This package is auto-updated.
Last update: 2024-09-07 20:25:33 UTC
README
Laravel API 枚举字典支持和验证库。
在API资源响应中人性化你的枚举。
安装
Composer
要开始安装,请通过composer CLI要求安装包
composer require synortix/laravel-dictionary:1.*
用法
定义字典
你可以通过扩展 Synortix\Dictionary\Dictionary 类来定义你的字典
use Synortix\Dictionary\Dictionary;
class CustomerTypeDictionary extends Dictionary
{
const FREE = 1;
const PAID = 2;
}
创建字典实例
你可以从字符串表示形式创建对象,并将其进一步作为对象传递。 字典字符串不区分大小写。
try {
$customerType = new CustomerTypeDictionary($request->get('customer_type'));
} catch (UnexpectedValueException $e) {
// invalid value, handle it here
}
在模型资源中使用
class CustomerResource extends Resource
{
public function toArray($request)
{
return [
'id' => $this->resource->id,
'type' => (string) new CustomerTypeDictionary($this->resource->type)
];
}
}
验证请求参数
$this->validate($request, [
'cusomer_type' => ['required', new DictionaryRule(CustomerTypeDictionary::class)],
]);
运行测试
为了测试目的,此库使用PHPUnit。要在自己的环境中运行测试,请执行以下命令。
clone git@github.com:synortix/laravel-dictionary.git
cd laravel-dictionary
composer install
php vendor/bin/phpunit --bootstrap vendor/autoload.php tests/
许可证
本项目采用MIT许可证 - 有关详细信息,请参阅LICENSE.md文件。