You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: core/state-providers.md
+63-1Lines changed: 63 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -17,7 +17,7 @@ In the following examples we will create custom state providers for an entity cl
17
17
Note, that if your entity is not Doctrine-related, you need to flag the identifier property by using
18
18
`#[ApiProperty(identifier: true)` for things to work properly (see also [Entity Identifier Case](serialization.md#entity-identifier-case)).
19
19
20
-
## State Provider
20
+
## Creating a Custom State Provider
21
21
22
22
If the [Symfony MakerBundle](https://symfony.com/doc/current/bundles/SymfonyMakerBundle) is installed in your project,
23
23
you can use the following command to generate a custom state provider easily:
@@ -124,3 +124,65 @@ use App\State\BlogPostProvider;
124
124
#[ApiResource(provider: BlogPostProvider::class)]
125
125
class BlogPost {}
126
126
```
127
+
128
+
## Hooking into the Built-In State Provider
129
+
130
+
If you want to execute custom business logic before or after retrieving data, this can be achieved by [decorating](https://symfony.com/doc/current/service_container/service_decoration.html) the built-in state providers or using [composition](https://en.wikipedia.org/wiki/Object_composition).
131
+
132
+
The next example uses a [DTO](https://api-platform.com/docs/core/dto/#using-data-transfer-objects-dtos) to change the presentation for data originally retrieved by the default state provider.
133
+
134
+
```php
135
+
<?php
136
+
137
+
namespace App\State;
138
+
139
+
use App\Dto\AnotherRepresentation;
140
+
use App\Model\Book;
141
+
use ApiPlatform\Metadata\Operation;
142
+
use ApiPlatform\State\ProviderInterface;
143
+
144
+
final class BookRepresentationProvider implements ProviderInterface
145
+
{
146
+
public function __construct(private ProviderInterface $itemProvider)
147
+
{
148
+
}
149
+
150
+
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
0 commit comments