Skip to content

Commit f9e0125

Browse files
authored
docs: implementing a write operation with a different output (#1687)
1 parent cfc0ed1 commit f9e0125

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

core/dto.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,77 @@ final class BookRepresentationProvider implements ProviderInterface
119119
}
120120
}
121121
```
122+
123+
## Implementing a Write Operation With an Output Different From the Resource
124+
125+
For returning another representation of your data in a [State Processor](./state-processors.md), you should specify your processor class in the `processor` attribute and same for your `output`.
126+
127+
[codeSelector]
128+
129+
```php
130+
<?php
131+
132+
namespace App\Entity;
133+
134+
use ApiPlatform\Metadata\Post;
135+
use App\Dto\AnotherRepresentation;
136+
use App\State\BookRepresentationProcessor;
137+
138+
#[Post(output: AnotherRepresentation::class, processor: BookRepresentationProcessor::class)]
139+
class Book {}
140+
```
141+
```yaml
142+
# api/config/api_platform/resources.yaml
143+
App\Entity\Book:
144+
operations:
145+
ApiPlatform\Metadata\Post:
146+
output: App\Dto\AnotherRepresentation
147+
processor: App\State\BookRepresentationProcessor
148+
```
149+
```xml
150+
<?xml version="1.0" encoding="UTF-8" ?>
151+
<!-- api/config/api_platform/resources.xml -->
152+
153+
<resources xmlns="https://api-platform.com/schema/metadata/resources-3.0"
154+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
155+
xsi:schemaLocation="https://api-platform.com/schema/metadata/resources-3.0
156+
https://api-platform.com/schema/metadata/resources-3.0.xsd">
157+
<resource class="App\Entity\Book">
158+
<operations>
159+
<operation class="ApiPlatform\Metadata\Post"
160+
processor="App\State\BookRepresentationProcessor"
161+
output="App\Dto\AnotherRepresentation" />
162+
</operations>
163+
</resource>
164+
</resources>
165+
```
166+
167+
[/codeSelector]
168+
169+
Here the `$data` attribute represents an instance of your resource.
170+
171+
```php
172+
<?php
173+
174+
namespace App\State;
175+
176+
use ApiPlatform\Metadata\Operation;
177+
use ApiPlatform\State\ProcessorInterface;
178+
use App\Dto\AnotherRepresentation;
179+
use App\Model\Book;
180+
181+
final class BookRepresentationProcessor implements ProcessorInterface
182+
{
183+
/**
184+
* @param Book $data
185+
*/
186+
public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
187+
{
188+
return new AnotherRepresentation(
189+
$data->getId(),
190+
$data->getTitle(),
191+
// etc.
192+
);
193+
}
194+
}
195+
```

0 commit comments

Comments
 (0)