Skip to content

Commit 9527ec5

Browse files
Complete example for Messenger with persistence (#1293)
1 parent 4431893 commit 9527ec5

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

core/data-persisters.md

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,53 @@ final class BlogPostDataPersister implements ContextAwareDataPersisterInterface,
184184
}
185185
```
186186

187-
This is very useful when using [`Messenger` with API Platform](messenger.md) as you may want to do something asynchronously with the data but still call the default Doctrine data persister.
187+
This is very useful when using [`Messenger` with API Platform](messenger.md) as you may want to do something asynchronously with the data but still call the default Doctrine data persister, for example:
188+
```php
189+
namespace App\DataPersister;
190+
191+
use ApiPlatform\Core\DataPersister\ContextAwareDataPersisterInterface;
192+
use Doctrine\ORM\EntityManagerInterface;
193+
use App\Entity\BlogPost;
194+
195+
final class BlogPostDataPersister implements ContextAwareDataPersisterInterface, ResumableDataPersisterInterface
196+
{
197+
private $entityManager;
198+
199+
public function __construct(EntityManagerInterface $entityManager)
200+
{
201+
$this->entityManager = $entityManager;
202+
}
203+
204+
public function supports($data, array $context = []): bool
205+
{
206+
return $data instanceof BlogPost;
207+
}
208+
209+
public function persist($data, array $context = [])
210+
{
211+
$this->entityManager->persist($data);
212+
$this->entityManager->flush();
213+
}
214+
215+
public function remove($data, array $context = [])
216+
{
217+
$this->entityManager->remove($data);
218+
$this->entityManager->flush();
219+
}
220+
221+
// Once called this data persister will resume to the next one
222+
public function resumable(array $context = []): bool
223+
{
224+
return true;
225+
}
226+
}
227+
```
228+
```yaml
229+
# api/config/services.yaml
230+
services:
231+
# ...
232+
App\DataPersister\BlogPostDataPersister: ~
233+
# Uncomment only if autoconfiguration is disabled
234+
#arguments: ['@App\DataPersister\BlogPostDataPersister.inner']
235+
#tags: [ 'api_platform.data_persister' ]
236+
```

0 commit comments

Comments
 (0)