sajad torkamani

In a nutshell

State processors are classes that receive an instance of a class marked as an API resource (e.g., typically using the #[ApiResource] attribute), and used to persist or update records in a data store (e.g., MySQL database).

You typically use state processors to handle POST, PUT, PATCH, or DELETE operations. State processors were released in API Platform 3 and replaced the previous data persistors API.

An example state processor

1. Create a state processor

Assuming you have the Symfony MakerBundle installed, you can run the below to quickly create a custom state processor:

bin/console make:state-processor

An example state processor looks like the following:

<?php

namespace App\State;

use App\Entity\BlogPost;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;

class BlogPostProcessor implements ProcessorInterface
{
    /**
     * {@inheritDoc}
     */
    public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
    {
        // call your persistence layer to save $data
        return $data;
    }
}

2. Configure operation to use the processor

<?php

namespace App\Entity;

use ApiPlatform\Metadata\Post;
use App\State\BlogPostProcessor;

#[Post(processor: BlogPostProcessor::class)]
class BlogPost {}

Sources

Leave a comment

Your email address will not be published. Required fields are marked *