@@ -350,3 +350,73 @@ use Swagger\Annotations as SWG;
350
350
*/
351
351
public function __invoke()
352
352
```
353
+
354
+ ### Specify an input and/or output class
355
+
356
+ For a given resource class, you may want to have a different representation of this class as input (write) or output (read).
357
+ To do so, a resource can take an input and/or an output class:
358
+
359
+ ``` php
360
+ <?php
361
+ // api/src/Entity/Data.php
362
+
363
+ namespace App\Entity;
364
+
365
+ use ApiPlatform\Core\Annotation\ApiResource;
366
+ use App\Dto\Input;
367
+ use App\Dto\Output;
368
+
369
+ /**
370
+ * @ApiResource(attributes={
371
+ * "input_class"=Input::class,
372
+ * "output_class"Output::class
373
+ * })
374
+ */
375
+ final class Data
376
+ {
377
+ }
378
+ ```
379
+
380
+ The ` input_class ` attribute will be used in the denormalization phase, when transforming the user data to a resource instance.
381
+ The ` output_class ` attribute will be used in the normalization phase, this class represents how the ` Data ` resource will be given in the ` Response ` .
382
+
383
+ To create a ` Data ` , we ` POST ` an ` Input ` and get back an ` Output ` in the response.
384
+ For this example to work, one could use the following ` DataPersister ` :
385
+
386
+ ``` php
387
+ <?php
388
+
389
+ namespace App\DataPersister;
390
+
391
+ use ApiPlatform\Core\DataPersister\DataPersisterInterface;
392
+ use App\Dto\Input;
393
+ use App\Dto\Output;
394
+
395
+ class InputDataPersister implements DataPersisterInterface
396
+ {
397
+ public function supports($data): bool
398
+ {
399
+ return $data instanceof Input;
400
+ }
401
+
402
+ /**
403
+ * {@inheritdoc}
404
+ */
405
+ public function persist($data)
406
+ {
407
+ $output = new Output();
408
+ $output->name = $data->name;
409
+ $output->id = 1;
410
+
411
+ return $output;
412
+ }
413
+
414
+ /**
415
+ * {@inheritdoc}
416
+ */
417
+ public function remove($data)
418
+ {
419
+ return null;
420
+ }
421
+ }
422
+ ```
0 commit comments