Skip to content

Instantly share code, notes, and snippets.

@soyuka
Created March 8, 2019 10:39
Show Gist options
  • Save soyuka/312526207073dc0edb6add81d15f6249 to your computer and use it in GitHub Desktop.
Save soyuka/312526207073dc0edb6add81d15f6249 to your computer and use it in GitHub Desktop.
CQRS with Api Platform

Thanks to the above configuration you can now send a InputTodo that'll be handled by the InputTodoHandler.

<?php
namespace App\DataTransformer;
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
use App\Entity\InputTodo;
use App\Entity\Todo;
final class DataTransformer implements DataTransformerInterface {
public function transform($object, string $to, array $context = [])
{
return $object;
}
public function supportsTransformation($object, string $to, array $context = []): bool
{
if (\is_object($object)) {
return false;
}
return Todo::class === $to && InputTodo::class === ($context['input']['class'] ?? null);
}
}
<?php
namespace App\Messenger;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use App\Entity\InputTodo;
final class InputTodoHandler implements MessageHandlerInterface {
public function __invoke(InputTodo $inputTodo) {
}
}
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
/**
* @ApiResource(
* collectionOperations={
* "get",
* "post"={
* "messenger"=true,
* "output"=false,
* "status"=202,
* "input"=InputTodo::class
* }
* })
* @ORM\Entity()
*/
class Todo
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
public function getId(): ?int
{
return $this->id;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
}
<?php
namespace App\Entity;
class InputTodo {
public $description;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment