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
43 changes: 43 additions & 0 deletions core/data-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,49 @@ final class BlogPostItemDataProvider implements ItemDataProviderInterface, Restr
}
}
```
## 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 BlogPostCollectionDataProvider 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 service.

```yaml
# api/config/services.yaml
services:
# ...
'App\DataProvider\BlogPostCollectionDataProvider':
bind:
$subresourceDataProvider: '@api_platform.doctrine.orm.default.subresource_data_provider'
```

## Community Data Providers

Expand Down