arimac/laravel-request-mapper
Composer 安装命令:
composer require arimac/laravel-request-mapper
包简介
README 文档
README
This component allow you to inject DTO object mapped from the Request to the action.
- Install
- Requirements
- Basic usage
- Nested object
- Mapped strategies
- Create custom mapped strategy
- How to create an custom exception?
- Project example
- Contributing
- Licence
- TODO
1. Install
You can install this package via composer using this command:
composer require maksi/laravel-request-mapper
The package will automatically register itself.
2. Requirements
PHP 7.1 or newer and Laravel 5.5 or newer
3. Basic usage
3.1 Create an DTO object
<?php declare(strict_types = 1); use Maksi\LaravelRequestMapper\Filling\RequestData\AllRequestData; final class RoomSearchRequestData extends AllRequestData { private $name; protected function init(array $data): void { $this->name = $data['name'] ?? null; } public function getName(): string { return $this->name; } }
Your DTO object should extend one of RequestData classes:
RequestData classes responsible for mapped strategies.
$data array in the init it is an array which return from the mapped strategies classes. Basically $data it is some data from the Request.
3.2 Inject to the action
DTO object can be injected to any type of action.
<?php declare(strict_types = 1); /** * @package App\Http\Controller */ class RoomSearchController { ... public function __invoke(RoomSearchRequestData $payload) // DTO object injected { } }
3.3 Validate DTO object
You can apply validation to the DTO object:
- before mapping data to the DTO (
laravelvalidation) - after mapping data to the DTO (
symfony annotationvalidation)
3.3.1 Apply laravel validation
Laravel validation applied for the RequestData object before object filling.
- You should create a class with validation rules. This class should implement
Maksi\LaravelRequestMapper\Validation\BeforeType\Laravel\ValidationRuleInterfaceinterface (in case, if you do no need change the validationmessagesandcustomAttributes, than you can extendMaksi\LaravelRequestMapper\Validation\BeforeType\Laravel\AbstractValidationRuleclass)
<?php declare(strict_types = 1); namespace Maksi\LaravelRequestMapper\Tests\Integration\LaravelNestedValidation\Stub; use Maksi\LaravelRequestMapper\Validation\BeforeType\Laravel\AbstractValidationRule; class ValidatorRule extends AbstractValidationRule { public function rules(): array { return [ 'nested' => 'array|required', 'title' => 'string|required', ]; } }
- In the next you should apply this rules to the DTO object. This should be done via
annotation.
<?php declare(strict_types = 1); namespace Maksi\LaravelRequestMapper\Tests\Integration\LaravelNestedValidation\Stub; use Maksi\LaravelRequestMapper\Filling\RequestData\JsonRequestData; use Maksi\LaravelRequestMapper\Validation\BeforeType\Laravel\Annotation\ValidationClass; /** * @ValidationClass(class="\Maksi\LaravelRequestMapper\Tests\Integration\LaravelNestedValidation\Stub\ValidatorRule") */ class RootRequestDataStub extends JsonRequestData { private $title; private $nested; protected function init(array $data): void { $this->title = $data['title'] ?? null; $this->nested = new NestedRequestDataStub($data['nested'] ?? []); } public function getTitle(): string { return $this->title; } public function getNested(): NestedRequestDataStub { return $this->nested; } }
string
@ValidationClass(class="\Maksi\LaravelRequestMapper\Tests\Integration\LaravelNestedValidation\Stub\ValidatorRule")
indicates that before filling current DTO should be appied \Maksi\LaravelRequestMapper\Tests\Integration\LaravelNestedValidation\Stub\ValidatorRule rules for the data which will be injected to the dto.
3.3.2 Apply symfony annotation validation
Annotation symfony validation applied to the properties in the RequestData object (So this validation appied after the creating and DTO object).
At the first you should add the @Type(type="annotation") annotation to the RequestData object. After this you can apply the validation to the DTO object (for more information please see symfony validation documentation)
<?php declare(strict_types = 1); namespace Maksi\LaravelRequestMapper\Tests\Integration\AnnotationValidation\Stub; use Maksi\LaravelRequestMapper\Filling\RequestData\AllRequestData; use Maksi\LaravelRequestMapper\Validation\Annotation\Type; use Symfony\Component\Validator\Constraints as Assert; /** * @Type(type="annotation") */ class AllRequestDataStub extends AllRequestData { /** * @Assert\Type(type="int") * @Assert\NotBlank() */ private $allAge; /** * @var string * @Assert\NotBlank() */ private $allTitle; protected function init(array $data): void { $this->allAge = $data['age'] ?? null; $this->allTitle = $data['title'] ?? null; } public function getAllTitle(): string { return $this->allTitle; } public function getAllAge(): int { return $this->allAge; } }
4. Nested object validation
4.1. Symfony annotation validation
In the same way you can create an nested DTO object, for example:
Root class
<?php declare(strict_types = 1); namespace Maksi\LaravelRequestMapper\Tests\Integration\AnnotationNestedValidation\Stub; use Maksi\LaravelRequestMapper\Filling\RequestData\JsonRequestData; use Maksi\LaravelRequestMapper\Validation\Annotation\Type; use Symfony\Component\Validator\Constraints as Assert; /** * @Type(type="annotation") */ class RootRequestDataStub extends JsonRequestData { /** * @Assert\NotBlank() * @Assert\Type(type="string") */ private $title; /** * @Assert\Valid() */ private $nested; // this property should have `Valid` annotation for validate nested object protected function init(array $data): void { $this->title = $data['title'] ?? null; $this->nested = new NestedRequestDataStub($data['nested'] ?? []); } public function getTitle(): string { return $this->title; } public function getNested(): NestedRequestDataStub { return $this->nested; } }
Nested class
<?php declare(strict_types = 1); namespace Maksi\LaravelRequestMapper\Tests\Integration\AnnotationNestedValidation\Stub; use Maksi\LaravelRequestMapper\Filling\RequestData\JsonRequestData; use Symfony\Component\Validator\Constraints as Assert; class NestedRequestDataStub extends JsonRequestData { /** * @Assert\NotBlank() * @Assert\Type(type="string") */ private $nestedTitle; protected function init(array $data): void { $this->nestedTitle = $data['title'] ?? null; } public function getTitle(): string { return $this->nestedTitle; } }
4.2. Laravel validation for nested
So, as a laravel validation applied before filling the RequestData object, than you should just create the same validation class as an for no nested validation.
<?php use Maksi\LaravelRequestMapper\Validation\BeforeType\Laravel\AbstractValidationRule; class ValidatorRule extends AbstractValidationRule { /** * @return array */ public function rules(): array { return [ 'nested' => 'array|required', 'title' => 'string|required', 'nested.title' => 'string|required', // nested object validation ]; } }
5. Mapped strategies
By default package has 3 strategies:
AllStrategy - responsible for filling data from the $request->all() array. If you want to use this strategy, than your RequestData object should extend AllRequestData class.
HeaderStrategy - responsible for filling data from the $request->header->all() array. If you want to use this strategy, than your RequestData object should extend HeaderRequestData class.
JsonStrategy - responsible for filling data from the $request->json()->all() array. If you want to use this strategy, than your RequestData object should extend JsonRequestData class.
6. Create custom mapped strategy
You can create a custom mapped strategies for our application.
6.1 Create custom strategy
You strategy should implement StrategyInterface;
<?php declare(strict_types = 1); namespace App\Http\RequestDataStrategy; use App\Http\RequestData\TeacherSearchRequestData; use Illuminate\Http\Request; use Maksi\LaravelRequestMapper\Filling\Strategies\StrategyInterface; use Maksi\LaravelRequestMapper\Filling\RequestData\RequestData; class TeacherSearchStrategy implements StrategyInterface { public function resolve(Request $request): array { return $request->all(); } public function support(Request $request, RequestData $object): bool { return $object instanceof TeacherSearchRequestData && $request->routeIs('teacher-search'); } }
Method support define is strategy available for resolve object. This method has 2 parameters $request and $object:
$requestas aRequestinstance$object- it is empty DTO instance, witch will be filled
Method resolve will return the array which will be injected to the DTO instance. This method accept $request object.
6.2 Create RequestData class for Strategy
You should extend RequestData in case if you want to create your own strategy
<?php declare(strict_types = 1); namespace App\Http\RequestData; use Maksi\LaravelRequestMapper\Filling\RequestData\RequestData; use Symfony\Component\Validator\Constraints as Assert; final class TeacherSearchRequestData extends RequestData { /** * @var string * * @Assert\NotBlank() * @Assert\Type(type="string") */ private $name; protected function init(array $data): void { $this->name = $data['name'] ?? null; } public function getName(): string { return $this->name; } }
6.3 Register your strategy in the ServiceProvider
You should add instance of your strategy to the Maksi\LaravelRequestMapper\StrategiesHandler via addStrategy method.
<?php declare(strict_types = 1); namespace App\Http\Provider; use App\Http\RequestDataStrategy\TeacherSearchStrategy; use Illuminate\Support\ServiceProvider; use Maksi\LaravelRequestMapper\FillingChainProcessor; /** * Class RequestMapperProvider * * @package App\Http\Provider */ class RequestMapperProvider extends ServiceProvider { /** * @param FillingChainProcessor $fillingChainProcessor */ public function boot(FillingChainProcessor $fillingChainProcessor): void { $fillingChainProcessor->addStrategy($this->app->make(TeacherSearchStrategy::class)); } }
7. Change validation exception
- Create Exception which will extend
\Maksi\LaravelRequestMapper\Validation\ResponseException\AbstractExceptionand implement toResponse method
For example:
<?php class StringException extends \Maksi\LaravelRequestMapper\Validation\ResponseException\AbstractException implements \Illuminate\Contracts\Support\Responsable { /** * Create an HTTP response that represents the object. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\JsonResponse */ public function toResponse($request) { return \Illuminate\Http\JsonResponse::create('Invalid data provided') ->setStatusCode(\Illuminate\Http\Response::HTTP_UNPROCESSABLE_ENTITY); } }
- Define in
config/laravel-request-mapper.phpexception-classkey
<?php declare(strict_types = 1); return [ 'exception-class' => \Maksi\LaravelRequestMapper\Validation\ResponseException\DefaultException::class, ];
8. Project example
You can see example of usage part of this package in https://github.com/E-ZSTU/rozklad-rest-api project.
Contributing
Please see CONTRIBUTING for details.
License
The MIT License (MIT). Please see License File for more information.
TODO
- think about https://www.reddit.com/r/laravel/comments/af843q/laravel_request_mapper/edx39cj
- think about https://www.reddit.com/r/laravel/comments/af843q/laravel_request_mapper/edx8mci
- delete symfony validation, since I`m not sure that is needed for the laravel community
- add integration tests for
change exception - add priority to the strategies
- how you can get this DTO from the middleware (just register
RequestDataas a singleton)
arimac/laravel-request-mapper 适用场景与选型建议
arimac/laravel-request-mapper 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 522 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 11 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「mapper」 「laravel」 「dto」 「request-mapper」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 arimac/laravel-request-mapper 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 arimac/laravel-request-mapper 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 arimac/laravel-request-mapper 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
data-mapper php library
Convention-based Alternative ORM
PHP library for the MUMSYS project
A simple library that allows transform any kind of data to native php data or whatever
Data transfer objects
Convert doctrine dbal query result to dto
统计信息
- 总下载量: 522
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 8
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-11-25