|
| 1 | +Symfony Request Objects |
| 2 | +=========================== |
| 3 | + |
| 4 | +[](https://travis-ci.org/fesor/request-objects) |
| 5 | +[](https://scrutinizer-ci.com/g/fesor/request-objects/?branch=master) |
| 6 | +[](https://packagist.org/packages/fesor/request-objects) |
| 7 | +[](https://packagist.org/packages/fesor/request-objects) |
| 8 | +[](https://packagist.org/packages/fesor/request-objects) |
| 9 | + |
| 10 | +**Note**: This library should not be considered as production ready until 1.0 release. |
| 11 | +Please provide your feedback to make it happen! |
| 12 | + |
| 13 | +## Why? |
| 14 | + |
| 15 | +Symfony Forms component is a very powerful tool for handling forms. But nowadays things have changed. |
| 16 | +Complex forms are handled mostly on the client side. As for simple forms `symfony/forms` has very large overhead. |
| 17 | + |
| 18 | +And in some cases you just don't have forms. For example, if you are developing an HTTP API, you probably just |
| 19 | +need to interact with request payload. So why not just wrap request payload in some user defined object and |
| 20 | +validate just it? This also encourages separation of concerns and will help you in case of API versioning. |
| 21 | + |
| 22 | +## Usage |
| 23 | + |
| 24 | +First of all, we need to install this package via composer: |
| 25 | + |
| 26 | +``` |
| 27 | +composer require fesor/request-objects |
| 28 | +``` |
| 29 | + |
| 30 | +And register the bundle: |
| 31 | + |
| 32 | +``` |
| 33 | + public function registerBundles() |
| 34 | + { |
| 35 | + $bundles = [ |
| 36 | + // ... |
| 37 | + new \Fesor\RequestObject\Bundle\RequestObjectBundle(), |
| 38 | + ]; |
| 39 | + } |
| 40 | +``` |
| 41 | + |
| 42 | +Bundle doesn't require any additional configuration, but you could also specify an error response |
| 43 | +provider service in bundle config. We will come back to this in "Handle validation errors" section. |
| 44 | + |
| 45 | +### Define your request objects |
| 46 | + |
| 47 | +All user defined requests should extend `Fesor\RequestObject\RequestObject`. Let's create a simple |
| 48 | +request object for user registration action: |
| 49 | + |
| 50 | +```php |
| 51 | +use Fesor\RequestObject\RequestObject; |
| 52 | +use Symfony\Component\Validator\Constraints as Assert; |
| 53 | + |
| 54 | +class RegisterUserRequest extends RequestObject |
| 55 | +{ |
| 56 | + public function rules() |
| 57 | + { |
| 58 | + return new Assert\Collection([ |
| 59 | + 'email' => new Assert\Email(['message' => 'Please fill in valid email']), |
| 60 | + 'password' => new Assert\Length(['min' => 4, 'minMessage' => 'Password is to short']), |
| 61 | + 'first_name' => new Assert\NotNull(['message' => 'Please provide your first name']), |
| 62 | + 'last_name' => new Assert\NotNull(['message' => 'Please provide your last name']) |
| 63 | + ]); |
| 64 | + } |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +After that we can just use it in our action: |
| 69 | + |
| 70 | +```php |
| 71 | +public function registerUserAction(RegisterUserRequest $request) |
| 72 | +{ |
| 73 | + // Do Stuff! Data is already validated! |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | +This bundle will bind validated request object to the `$request` argument. Request object has very simple interface |
| 78 | + for data interaction. It is very similar to Symfony's request object but is considered immutable by default (although you |
| 79 | + can add some setters if you wish so) |
| 80 | + |
| 81 | +```php |
| 82 | +// returns value from payload by specific key or default value if provided |
| 83 | +$request->get('key', 'default value'); |
| 84 | + |
| 85 | +// returns whole payload |
| 86 | +$request->all(); |
| 87 | +``` |
| 88 | + |
| 89 | +### Where payload comes from? |
| 90 | + |
| 91 | +This library has default implementation of `PayloadResolver` interface, which acts this way: |
| 92 | + |
| 93 | +1) If a request can have a body (i.e. it is POST, PUT, PATCH or whatever request with body) |
| 94 | +it uses union of `$request->request->all()` and `$request->files->all()` arrays as payload. |
| 95 | + |
| 96 | +2) If request can't have a body (i.e. GET, HEAD verbs), then it uses `$request->query->all()`. |
| 97 | + |
| 98 | +If you wish to apply custom logic for payload extraction, you could implement `PayloadResolver` interface within |
| 99 | +your request object: |
| 100 | + |
| 101 | +```php |
| 102 | +class CustomizedPayloadRequest extends RequestObject implements PayloadResolver |
| 103 | +{ |
| 104 | + public function resolvePayload(Request $request) |
| 105 | + { |
| 106 | + $query = $request->query->all(); |
| 107 | + // turn string to array of relations |
| 108 | + if (isset($query['includes'])) { |
| 109 | + $query['includes'] = explode(',', $query['includes']); |
| 110 | + } |
| 111 | + |
| 112 | + return $query; |
| 113 | + } |
| 114 | +} |
| 115 | +``` |
| 116 | + |
| 117 | +This will allow you to do some crazy stuff with your requests and DRY a lot of stuff. |
| 118 | + |
| 119 | + |
| 120 | +### Validating payload |
| 121 | + |
| 122 | +As you can see from previous example, the `rules` method should return validation rules for [symfony validator](http://symfony.com/doc/current/book/validation.html). |
| 123 | +Your request payload will be validated against it and you will get valid data in your action. |
| 124 | + |
| 125 | +If you have some validation rules which depend on payload data, then you can handle it via validation groups. |
| 126 | + |
| 127 | +**Please note**: due to limitations in `Collection` constraint validator it is not so handy to use groups. |
| 128 | + So instead it is recommended to use `Callback` validator in tricky cases with dependencies on payload data. |
| 129 | + See [example](examples/Request/ContextDependingRequest.php) for details about problem. |
| 130 | + |
| 131 | +You may provide validation group by implementing `validationGroup` method: |
| 132 | + |
| 133 | +```php |
| 134 | +public function validationGroup(array $payload) |
| 135 | +{ |
| 136 | + return isset($payload['context']) ? |
| 137 | + ['Default', $payload['context']] : null; |
| 138 | +} |
| 139 | +``` |
| 140 | + |
| 141 | +### Handling validation errors |
| 142 | + |
| 143 | +If validated data is invalid, library will throw exception which will contain validation errors and request object. |
| 144 | + |
| 145 | +But if you don't want to handle it via `kernel.exception` listener, you have several options. |
| 146 | + |
| 147 | +First is to use your controller action to handle errors: |
| 148 | + |
| 149 | +```php |
| 150 | + |
| 151 | +public function registerUserAction(RegisterUserRequest $request, ConstraintViolationList $errors) |
| 152 | +{ |
| 153 | + if (0 !== count($errors)) { |
| 154 | + // handle errors |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +``` |
| 159 | + |
| 160 | +But this not so handy and will break DRY if you just need to return common error response. Thats why |
| 161 | +library provides you `ErrorResponseProvider` interface. You can implement it in your request object and move this |
| 162 | +code to `getErrorResponse` method: |
| 163 | + |
| 164 | +```php |
| 165 | +public function getErrorResponse(ConstraintViolationListInterface $errors) |
| 166 | +{ |
| 167 | + return new JsonResponse([ |
| 168 | + 'message' => 'Please check your data', |
| 169 | + 'errors' => array_map(function (ConstraintViolation $violation) { |
| 170 | + |
| 171 | + return [ |
| 172 | + 'path' => $violation->getPropertyPath(), |
| 173 | + 'message' => $violation->getMessage() |
| 174 | + ]; |
| 175 | + }, iterator_to_array($errors)) |
| 176 | + ], 400); |
| 177 | +} |
| 178 | +``` |
| 179 | + |
| 180 | +## More examples |
| 181 | + |
| 182 | +If you're still not sure is it useful for you, please see the `examples` directory for more use cases. |
| 183 | +Didn't find your case? Then share your use case in issues! |
| 184 | + |
| 185 | +## Contribution |
| 186 | + |
| 187 | +Feel free to give feedback and feature requests or post issues. PR's are welcomed! |
0 commit comments