Skip to content

Commit de8478d

Browse files
committed
add provider
1 parent 3d444f6 commit de8478d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

laravel/index.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,9 +165,65 @@ So, if you want to access the raw data, you have two alternatives:
165165

166166
For instance, go to `http://127.0.0.1:8000/api/books.jsonld` to retrieve the list of `Book` resources in JSON-LD.
167167

168+
> [!NOTE] Read the next parameter if you want to use JSON:API instead!
169+
168170
Of course, you can also use your favorite HTTP client to query the API.
169171
We are fond of [Hoppscotch](https://hoppscotch.com), a free and open source API client with good support of API Platform.
170172

173+
As recommended by our [design considerations](../core/design.md), you can totally use the data source of your choice using a [provider](../core/state-providers.md):
174+
175+
```php
176+
<?php
177+
178+
namespace App\State;
179+
180+
use ApiPlatform\Metadata\Operation;
181+
use ApiPlatform\State\ProviderInterface;
182+
183+
final class BookProvider implements ProviderInterface
184+
{
185+
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
186+
{
187+
return new Book(id: $uriVariables['id']);
188+
}
189+
}
190+
```
191+
192+
Register the state provider:
193+
194+
```php
195+
<?php
196+
197+
namespace App\Providers;
198+
199+
use Illuminate\Contracts\Foundation\Application;
200+
use Illuminate\Support\ServiceProvider;
201+
202+
class ApiServiceProvider extends ServiceProvider
203+
{
204+
public function register(): void
205+
{
206+
$this->app->singleton(BookProvider::class, function (Application $app) {
207+
return new BookProvider();
208+
});
209+
210+
$this->app->tag([BookProvider::class], ProviderInterface::class);
211+
}
212+
}
213+
```
214+
215+
Apply the provider to your operation:
216+
217+
```php
218+
<?php
219+
220+
#[Get(provider: BookProvider::class)]
221+
class Book
222+
{
223+
public string $id;
224+
}
225+
```
226+
171227
## Content Negotiation
172228

173229
By default, a JSON-LD response is sent [but many other formats, including CSV and JSON:API are supported](../core/content-negotiation.md).

0 commit comments

Comments
 (0)