pugx / bindto
将请求绑定到 DTO/命令的简单方法
v0.1.1
2016-04-21 07:20 UTC
Requires
- php: >=5.5
- doctrine/common: ^2.6
- liuggio/filler-dto: ^0.1.0
- psr/http-message: ^1.0
- symfony/validator: ^2.7|^3.0
Requires (Dev)
- phpunit/phpunit: ~4.7|~5.0
- symfony/http-foundation: ^3.0
This package is auto-updated.
Last update: 2024-09-18 23:01:23 UTC
README
将请求绑定到 DTO/命令的最简单方法。
Bindto 帮助您使用 DTO 和命令与 API 和数据验证一起工作。
它非常快(不使用反射)并将请求与您的类绑定。
这是停止使用缓慢且复杂的 Symfony 表单组件进行 API 的最聪明方式。
安装
composer require pugx/bindto
使用方法
例如,您需要创建一个 Post/Patch/Put API
1. 创建一个简单的类,作为请求的主体
提示:您可以使用 Symfony 验证组件注解
use Symfony\Component\Validator\Constraints as Assert; Class CreateFeedback { /** * @Assert\NotBlank(groups={"POST"}) * @Assert\Type(type="string") */ public $subject; /** * @Assert\NotNull(groups={"POST"}) * @Assert\Type(type="string") * @Assert\Length( * min = 10, * max = 500) */ public $body; }
2. 在您的控制器中
如果您使用 Silex,可能希望强制输入验证,请参考 http://silex.sensiolabs.org/doc/usage.html#example-post-route
require_once __DIR__.'/../vendor/autoload.php'; use Bindto\Binder; $app = new Silex\Application(); $app->post('/feedback', function (Request $request) { $binder = Binder::createSimpleProductionBinder(); $result = $binder->bind($request, CreateFeedback::class); if (!$result->isValid()) { throw new \Exception($result->getViolations()); } $createFeedBack = $result->getData(); mail($createFeedBack->subject, '[YourSite] Feedback', $createFeedBack->body); return new Response('Thank you for your feedback!', 201); }); $app->run();
支持 PATCH 部分修改
如果您想部分 PATCH,请使用验证组
/** * @Assert\NotNull(groups={"POST"}) * @Assert\Type(type="string") * @Assert\Length( * min = 10, * max = 500) */ public $body;
使用 POST 请求将使用所有断言,而使用 PUT 和 PATCH 仅使用 Type
和 Length
断言。
待办事项
- 递归绑定器?
- 集合?
- twig 辅助函数?
- 测试将 maptest 从 bindertest 解耦
- Silex 提供者?
- sf 插件?
运行测试
composer dump-autoload bin/phpunit