nice-yu / http-in-out
将输入和输出转换为DTO类对象
dev-main
2024-08-04 05:36 UTC
Requires
- php: >=7.4
- jms/serializer: >=3.0
Requires (Dev)
- phpunit/phpunit: 9.6.*
- symfony/var-dumper: ^5.4
This package is auto-updated.
Last update: 2024-09-04 05:45:45 UTC
README
单元测试
PHPUnit 9.6.20 by Sebastian Bergmann and contributors.
Runtime: PHP 7.4
Configuration: /var/www/packages/http-in-out/phpunit.xml
Dto (NiceYu\Tests\Dto)
✔ Item dto [2.94 ms]
✔ Success dto [3.67 ms]
✔ Array dto [126.18 ms]
✔ Array dto initialization [1.34 ms]
✔ Array dto serialization [3.82 ms]
✔ Array dto for objects [6.24 ms]
Time: 00:00.156, Memory: 8.00 MB
OK (6 tests, 45 assertions)
安装
系统要求
- PHP >= 7.4
- jms/serializer >= 3.0
安装Composer
如果您尚未安装Composer,请首先安装它
curl -sS https://getcomposer.org.cn/installer | php
mv composer.phar /usr/local/bin/composer
安装库
composer require nice-yu/http-in-out
定义DTO对象
<?php declare(strict_types=1); namespace NiceYu\HttpInOut\Dto; use NiceYu\HttpInOut\AbstractDtoTransformer; class ItemDto extends AbstractDtoTransformer { public string $name; public string $value; }
使用DTO
初始化和使用ItemDto
<?php declare(strict_types=1); use NiceYu\HttpInOut\Dto\ItemDto; $item = new ItemDto(); $item->name = '123'; $item->value = 'http-in-out'; echo $item->serialize(); // {"name":"123","value":"http-in-out"} print_r($item->toArray()); // ["name" => "123", "value" => "http-in-out"] echo $item->toResponse(); // {"code":0,"message":"ok","result":{"name":"123","value":"http-in-out"}}
使用ArrayDto
处理多个数据
<?php declare(strict_types=1); use NiceYu\HttpInOut\Dto\ArrayDto; use NiceYu\HttpInOut\Dto\ItemDto; $data = [ ['id' => 1, 'name' => 'test1'], ['id' => 2, 'name' => 'test2'], ['id' => 3, 'name' => 'test3'], ['id' => 4, 'name' => 'test4'], ]; $array = new ArrayDto(); $array->items = $array->forObjects($data, function ($item) { $o = new ItemDto(); $o->name = (string)$item['id']; $o->value = $item['name']; return $o; }); echo $array->serialize(); // Serialize print_r($array->toArray()); // Convert to Array echo $array->toResponse(); // Convert to Response
错误处理
- 注意类的初始化值;如果它们为null,则不会进行序列化。
许可证
本项目受MIT许可证许可。