Installation:
composer require api-platform/jsonld
Add the bundle to config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel via bridge if applicable).
First Use Case:
JsonLdContextBuilder to generate JSON-LD contexts for API responses:
use ApiPlatform\JsonLd\JsonLdContextBuilder;
$contextBuilder = new JsonLdContextBuilder();
$context = $contextBuilder->buildFromResourceClass(MyResource::class);
JsonLdContextBuilder in a custom service.Where to Look First:
src/JsonLdContextBuilder.php for core logic.tests/ for usage examples.Dynamic Context Generation:
JsonLdContextBuilder to auto-generate contexts from Doctrine entities or API resources:
$context = $contextBuilder->buildFromResourceClass(User::class);
@ApiResource(context="custom:context")).Manual Context Definition:
$context = [
'@context' => [
'name' => '@id',
'homePage' => {
'@id': 'foaf:homepage',
'@type': '@id'
}
]
];
Integration with API Platform:
JsonLdContextBuilder to add custom logic:
class CustomContextBuilder extends JsonLdContextBuilder {
protected function getContextForClass(string $class): array {
$context = parent::getContextForClass($class);
$context['@context'][] = 'https://custom-schema.org';
return $context;
}
}
$this->app->bind(JsonLdContextBuilder::class, CustomContextBuilder::class);
Response Transformation:
$response->headers->set('Content-Type', 'application/ld+json');
$response->setContent(json_encode($data, JSON_LD));
@ApiResource and @ApiProperty for metadata-driven contexts.symfony/serializer for flexible normalization.$context = Cache::remember("jsonld_context_{$class}", 3600, fn() => $contextBuilder->buildFromResourceClass($class));
Namespace Collisions:
@context definitions. Validate contexts before merging:
if (!isset($mergedContext['@context']['customTerm'])) {
$mergedContext['@context']['customTerm'] = 'http://example.org/customTerm';
}
Circular References:
@MaxDepth or @Groups (Symfony Serializer) to limit traversal.Laravel-Specific Quirks:
api-platform/core or manually adapt the JsonLdContextBuilder.Performance:
\Log::debug('Generated context:', ['context' => $context]);
@ApiResource and @ApiProperty are correctly applied to entities.Custom Context Providers:
Implement ContextProviderInterface to inject dynamic contexts:
class CustomContextProvider implements ContextProviderInterface {
public function getContext(string $resourceClass): array {
return ['@context' => ['custom' => 'http://example.org']];
}
}
Event Listeners:
Hook into api_platform.jsonld.context_builder events (Symfony) or Laravel’s events to modify contexts.
Hybrid Serialization:
Combine with api-platform/core’s SerializerContextBuilder for mixed JSON/JSON-LD responses.
Testing:
Mock JsonLdContextBuilder in unit tests:
$builder = $this->createMock(JsonLdContextBuilder::class);
$builder->method('buildFromResourceClass')->willReturn(['@context' => []]);
How can I help you explore Laravel packages today?