-
-
Notifications
You must be signed in to change notification settings - Fork 901
/
Copy pathprovide-the-resource-state.php
63 lines (53 loc) · 2.01 KB
/
provide-the-resource-state.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
// ---
// slug: provide-the-resource-state
// name: Provide the Resource State
// position: 2
// executable: true
// tags: design, state
// ---
// Our model is the same then in the previous guide ([Declare a Resource](/playground/declare-a-resource). API Platform will declare
// CRUD operations if we don't declare them.
namespace App\ApiResource {
use ApiPlatform\Metadata\ApiResource;
use App\State\BookProvider;
// We use a `BookProvider` as the [ApiResource::provider](/docs/reference/Metadata/ApiResource#provider) option.
#[ApiResource(provider: BookProvider::class)]
class Book
{
public string $id;
}
}
namespace App\State {
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResource\Book;
// The BookProvider is where we retrieve the data in our persistence layer.
// In this provider we choose to handle the retrieval of a single Book but also a list of Books.
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';
/* $book2 = new Book();
* $book2->id = '2'; */
// As an exercise you can edit the code and add a second book in the collection.
return [$book/* $book2 */];
}
$book = new Book();
// The value at `$uriVariables['id']` is the one that matches the `{id}` variable of the **[URI template](/docs/core/subresources/)**.
$book->id = $uriVariables['id'];
return $book;
}
}
}
namespace App\Playground {
use Symfony\Component\HttpFoundation\Request;
function request(): Request
{
return Request::create('/books.jsonld', 'GET');
}
}