@@ -125,6 +125,45 @@ services:
125
125
tags: [ 'api_platform.item_data_provider' ]
126
126
` ` `
127
127
128
+ # # Injecting the Serializer in an `ItemDataProvider`
129
+
130
+ In some cases, you may need to inject the `Serializer` in your `DataProvider`. There are no issues with the
131
+ ` CollectionDataProvider` , but when injecting it in the `ItemDataProvider` it will throw a `CircularReferenceException`.
132
+
133
+ For this reason, we implemented the `SerializerAwareDataProviderInterface` :
134
+
135
+ ` ` ` php
136
+ <?php
137
+ // src/AppBundle/DataProvider/BlogPostItemDataProvider.php
138
+
139
+ namespace AppBundle\D ataProvider;
140
+
141
+ use ApiPlatform\C ore\D ataProvider\I temDataProviderInterface;
142
+ use ApiPlatform\C ore\D ataProvider\S erializerAwareDataProviderInterface;
143
+ use ApiPlatform\C ore\D ataProvider\S erializerAwareDataProviderTrait;
144
+ use ApiPlatform\C ore\E xception\R esourceClassNotSupportedException;
145
+ use AppBundle\E ntity\B logPost;
146
+
147
+ final class BlogPostItemDataProvider implements ItemDataProviderInterface, SerializerAwareDataProviderInterface
148
+ {
149
+ use SerializerAwareDataProviderTrait;
150
+
151
+ public function supports(string $resourceClass, string $operationName = null): bool
152
+ {
153
+ return BlogPost::class === $resourceClass;
154
+ }
155
+
156
+ public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): ?BlogPost
157
+ {
158
+ // Retrieve data from anywhere you want, in a custom format
159
+ $data = '...';
160
+
161
+ // Deserialize data using the Serializer
162
+ return $this->getSerializer()->deserialize($data, BlogPost::class, 'custom');
163
+ }
164
+ }
165
+ ` ` `
166
+
128
167
Previous chapter : [Extending JSON-LD context](extending-jsonld-context.md)
129
168
130
169
Next chapter : [Extensions](extensions.md)
0 commit comments