Skip to content

Commit 6fb4310

Browse files
Add Laravel support to state processors documentation (#2019)
Co-authored-by: Antoine Bluchet <soyuka@users.noreply.github.com>
1 parent 6c43cc1 commit 6fb4310

File tree

1 file changed

+156
-2
lines changed

1 file changed

+156
-2
lines changed

core/state-processors.md

Lines changed: 156 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,13 @@ classes called **state processors**. State processors receive an instance of the
55
the `#[ApiResource]` attribute). This instance contains data submitted by the client during [the deserialization
66
process](serialization.md).
77

8-
A state processor using [Doctrine ORM](https://www.doctrine-project.org/projects/orm.html) is included with the library and
8+
With the Symfony variant, a state processor using [Doctrine ORM](https://www.doctrine-project.org/projects/orm.html) is included with the library and
99
is enabled by default. It is able to persist and delete objects that are also mapped as [Doctrine entities](https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/basic-mapping.html).
1010
A [Doctrine MongoDB ODM](https://www.doctrine-project.org/projects/mongodb-odm.html) state processor is also included and can be enabled by following the [MongoDB documentation](mongodb.md).
1111

12+
With the Laravel variant, a state processor using [Eloquent ORM](https://laravel.com/docs/eloquent) is included with the library and
13+
is enabled by default. It is able to persist and delete objects that are also mapped as [Related Models](https://laravel.com/docs/eloquent-relationships#inserting-and-updating-related-models).
14+
1215
However, you may want to:
1316

1417
- store data to other persistence layers (Elasticsearch, external web services...)
@@ -20,6 +23,7 @@ process the data for a given resource will be used.
2023

2124
## Creating a Custom State Processor
2225

26+
### Custom State Processor with Symfony
2327
If the [Symfony MakerBundle](https://symfony.com/doc/current/bundles/SymfonyMakerBundle) is installed in your project, you can use the following command to generate a custom state processor easily:
2428

2529
```console
@@ -75,8 +79,64 @@ use App\State\BlogPostProcessor;
7579
class BlogPost {}
7680
```
7781

82+
### Custom State Processor with Laravel
83+
Using [Laravel Artisan Console](https://laravel.com/docs/artisan), you can generate a custom state processor easily with the following command:
84+
```console
85+
php artisan make:state-processor
86+
```
87+
88+
To create a state processor, you have to implement the [`ProcessorInterface`](https://github.com/api-platform/core/blob/main/src/State/ProcessorInterface.php).
89+
This interface defines a method `process`: to create, delete, update, or alter the given data in any ways.
90+
91+
Here is an implementation example:
92+
93+
```php
94+
<?php
95+
// api/app/State/BlogPostProcessor.php
96+
97+
namespace App\State;
98+
99+
use App\Models\BlogPost;
100+
use ApiPlatform\Metadata\Operation;
101+
use ApiPlatform\State\ProcessorInterface;
102+
103+
/**
104+
* @implements ProcessorInterface<BlogPost, BlogPost|void>
105+
*/
106+
final class BlogPostProcessor implements ProcessorInterface
107+
{
108+
/**
109+
* @return BlogPost|void
110+
*/
111+
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
112+
{
113+
// call your persistence layer to save $data
114+
return $data;
115+
}
116+
}
117+
```
118+
119+
The `process()` method must return the created or modified object, or nothing (that's why `void` is allowed) for `DELETE` operations.
120+
The `process()` method can also take an object as input, in the `$data` parameter, that isn't of the same type that its output (the returned object). See [the DTO documentation entry](dto.md) for more details.
121+
122+
We then configure our operation to use this processor:
123+
124+
```php
125+
<?php
126+
// api/app/Models/BlogPost.php
127+
128+
namespace App\Models;
129+
130+
use ApiPlatform\Metadata\Post;
131+
use App\State\BlogPostProcessor;
132+
133+
#[Post(processor: BlogPostProcessor::class)]
134+
class BlogPost {}
135+
```
136+
78137
## Hooking into the Built-In State Processors
79138

139+
### Symfony State Processor mechanism
80140
If you want to execute custom business logic before or after persistence, this can be achieved by using [composition](https://en.wikipedia.org/wiki/Object_composition).
81141

82142
Here is an implementation example which uses [Symfony Mailer](https://symfony.com/doc/current/mailer.html) to send new users a welcome email after a REST `POST` or GraphQL `create` operation, in a project using the native Doctrine ORM state processor:
@@ -151,7 +211,101 @@ use App\State\UserProcessor;
151211
class User {}
152212
```
153213

154-
## Registering Services Without Autowiring
214+
### Laravel State Processor mechanism
215+
If you want to execute custom business logic before or after persistence, this can be achieved by using [composition](https://en.wikipedia.org/wiki/Object_composition).
216+
217+
Here is an implementation example which uses [Laravel Mail](https://laravel.com/docs/mail) to send new users a welcome email after a REST `POST` or GraphQL `create` operation, in a project using the native Eloquent ORM state processor:
218+
219+
```php
220+
<?php
221+
// api/app/State/UserProcessor.php
222+
223+
namespace App\State;
224+
225+
use ApiPlatform\Metadata\DeleteOperationInterface;
226+
use ApiPlatform\Metadata\Operation;
227+
use ApiPlatform\State\ProcessorInterface;
228+
use App\Models\User;
229+
use Symfony\Component\DependencyInjection\Attribute\Autowire;
230+
use Symfony\Component\Mailer\MailerInterface;
231+
232+
/**
233+
* @implements ProcessorInterface<User, User|void>
234+
*/
235+
final class UserProcessor implements ProcessorInterface
236+
{
237+
public function __construct(
238+
private ProcessorInterface $persistProcessor,
239+
private ProcessorInterface $removeProcessor,
240+
)
241+
{
242+
}
243+
244+
/**
245+
* @return User|void
246+
*/
247+
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
248+
{
249+
if ($operation instanceof DeleteOperationInterface) {
250+
return $this->removeProcessor->process($data, $operation, $uriVariables, $context);
251+
}
252+
253+
$result = $this->persistProcessor->process($data, $operation, $uriVariables, $context);
254+
$this->sendWelcomeEmail($data);
255+
256+
return $result;
257+
}
258+
259+
private function sendWelcomeEmail(User $user): void
260+
{
261+
// Your welcome email logic...
262+
// Mail::to($user->getEmail())->send(new WelcomeMail($user));
263+
}
264+
}
265+
```
266+
267+
Don't forget to tag the service with the `PersistProcessor` and the `RemoveProcessor` state classes.
268+
269+
```php
270+
<?php
271+
272+
namespace App\Providers;
273+
274+
use ApiPlatform\Laravel\Eloquent\State\PersistProcessor;
275+
use ApiPlatform\Laravel\Eloquent\State\RemoveProcessor;
276+
use App\State\UserProcessor;
277+
use Illuminate\Support\ServiceProvider;
278+
279+
class AppServiceProvider extends ServiceProvider
280+
{
281+
public function register(): void
282+
{
283+
$this->app->tag([UserProcessor::class], [PersistProcessor::class, RemoveProcessor::class,]);
284+
}
285+
286+
public function boot(): void
287+
{
288+
}
289+
}
290+
```
291+
If you're using Laravel MongoDB ODM instead of Eloquent ORM, make sure you're using the right services.
292+
293+
Finally, configure that you want to use this processor on the User resource:
294+
295+
```php
296+
<?php
297+
// api/app/Models/User.php
298+
299+
namespace App\Models;
300+
301+
use ApiPlatform\Metadata\ApiResource;
302+
use App\State\UserProcessor;
303+
304+
#[ApiResource(processor: UserProcessor::class)]
305+
class User {}
306+
```
307+
308+
## Registering Services Without Autowiring (only for the Symfony variant)
155309

156310
The previous examples work because service autowiring and autoconfiguration are enabled by default in Symfony and API Platform.
157311
If you disabled this feature, you need to register the services by yourself and add the `api_platform.state_processor` tag.

0 commit comments

Comments
 (0)