Guides
Tutorials
Our model is the same then in the previous guide (Declare a Resource. API Platform will declare CRUD operations if we don't declare them.
// src/App/ApiResource.php
namespace App\ApiResource;
use ApiPlatform\Metadata\ApiResource;
use App\State\BookProvider;// src/App/ApiResource.php
namespace App\ApiResource;
use ApiPlatform\Metadata\ApiResource;
use App\State\BookProvider;We use a BookProvider as the ApiResource::provider option.
#[ApiResource(provider: BookProvider::class)]
class Book
{
public string $id;
}
// src/App/State.php
namespace App\State;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResource\Book;#[ApiResource(provider: BookProvider::class)]
class Book
{
public string $id;
}
// src/App/State.php
namespace App\State;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResource\Book;final class BookProvider implements ProviderInterface
{
public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable|object|null
{
if ($operation instanceof CollectionOperationInterface) {
$book = new Book();
$book->id = '1';final class BookProvider implements ProviderInterface
{
public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable|object|null
{
if ($operation instanceof CollectionOperationInterface) {
$book = new Book();
$book->id = '1'; return [$book];
}
$book = new Book(); return [$book];
}
$book = new Book();The value at $uriVariables['id'] is the one that matches the {id} variable of the URI template.
$book->id = $uriVariables['id'];
return $book;
}
} $book->id = $uriVariables['id'];
return $book;
}
}