Skip to content

add: [DOC] Custom Subresources Data Provider examples #1454

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 20, 2022
45 changes: 45 additions & 0 deletions core/data-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ For a given resource, you can implement two kinds of interface:
is used when fetching a collection.
* the [`ItemDataProviderInterface`](https://github.com/api-platform/core/blob/main/src/Core/DataProvider/ItemDataProviderInterface.php)
is used when fetching items.
* the [`SubresourceDataProviderInterface`](https://github.com/api-platform/core/blob/2.6/src/DataProvider/SubresourceDataProviderInterface.php)
is used when fetching items.

Both implementations can also implement a third, optional, interface called
['RestrictedDataProviderInterface'](https://github.com/api-platform/core/blob/main/src/Core/DataProvider/RestrictedDataProviderInterface.php)
Expand Down Expand Up @@ -126,6 +128,49 @@ services:

You can find a full working example in the [API Platform's demo application](https://github.com/api-platform/demo/blob/main/api/src/DataProvider/TopBookItemDataProvider.php).

## Custom Subresources Data Provider

You can add custom logic or update subresources data provider with the SubresourceDataProviderInterface .

```php
<?php
// api/src/DataProvider/BlogPostCollectionDataProvider.php

namespace App\DataProvider;

use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\Entity\BlogPost;

final class BlogPostSubresourceDataProvider implements SubresourceDataProviderInterface, RestrictedDataProviderInterface
{
public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
{
return BlogPost::class === $resourceClass;
}

public function getSubresource(string $resourceClass, array $identifiers, array $context, string $operationName = null): iterable
{
// Retrieve the blog post collection from somewhere
$blogPosts = $this->subresourceDataProvider->getSubresource($resourceClass, $identifiers, $context, $operationName);
// write your own logic

return blogPosts;
}
}
```

Declare the service in your services configuration:

```yaml
# api/config/services.yaml
services:
# ...
'App\DataProvider\BlogPostSubresourceDataProvider':
arguments:
- '@api_platform.doctrine.orm.default.subresource_data_provider'
```

## Injecting the Serializer in an `ItemDataProvider`

In some cases, you may need to inject the `Serializer` in your `DataProvider`. There are no issues with the
Expand Down