Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Jsonld Laravel Package

api-platform/jsonld

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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).

  2. First Use Case:

    • For Laravel, use the JsonLdContextBuilder to generate JSON-LD contexts for API responses:
      use ApiPlatform\JsonLd\JsonLdContextBuilder;
      
      $contextBuilder = new JsonLdContextBuilder();
      $context = $contextBuilder->buildFromResourceClass(MyResource::class);
      
    • Integrate with API Platform (if used) by extending JsonLdContextBuilder in a custom service.
  3. Where to Look First:

    • Documentation (if available).
    • src/JsonLdContextBuilder.php for core logic.
    • tests/ for usage examples.

Implementation Patterns

Workflows

  1. Dynamic Context Generation:

    • Use JsonLdContextBuilder to auto-generate contexts from Doctrine entities or API resources:
      $context = $contextBuilder->buildFromResourceClass(User::class);
      
    • Override defaults via annotations (e.g., @ApiResource(context="custom:context")).
  2. Manual Context Definition:

    • For static contexts, define them in a service:
      $context = [
          '@context' => [
              'name' => '@id',
              'homePage' => {
                  '@id': 'foaf:homepage',
                  '@type': '@id'
              }
          ]
      ];
      
  3. Integration with API Platform:

    • Extend 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;
          }
      }
      
    • Bind the custom builder in Laravel’s service container:
      $this->app->bind(JsonLdContextBuilder::class, CustomContextBuilder::class);
      
  4. Response Transformation:

    • Use middleware to inject JSON-LD headers or transform responses:
      $response->headers->set('Content-Type', 'application/ld+json');
      $response->setContent(json_encode($data, JSON_LD));
      

Integration Tips

  • Doctrine Annotations: Leverage @ApiResource and @ApiProperty for metadata-driven contexts.
  • Symfony Serializer: Combine with symfony/serializer for flexible normalization.
  • Caching: Cache generated contexts to avoid redundant processing:
    $context = Cache::remember("jsonld_context_{$class}", 3600, fn() => $contextBuilder->buildFromResourceClass($class));
    

Gotchas and Tips

Pitfalls

  1. Namespace Collisions:

    • JSON-LD contexts may conflict with existing @context definitions. Validate contexts before merging:
      if (!isset($mergedContext['@context']['customTerm'])) {
          $mergedContext['@context']['customTerm'] = 'http://example.org/customTerm';
      }
      
  2. Circular References:

    • Deeply nested entities may cause infinite loops. Use @MaxDepth or @Groups (Symfony Serializer) to limit traversal.
  3. Laravel-Specific Quirks:

    • The package is primarily Symfony-based. For Laravel, use a bridge like api-platform/core or manually adapt the JsonLdContextBuilder.
    • Service registration may require manual binding (no auto-wiring in some Laravel versions).
  4. Performance:

    • Generating contexts for large schemas can be slow. Precompute and cache contexts for critical resources.

Debugging

  • Validate JSON-LD: Use tools like JSON-LD Playground to validate output.
  • Log Contexts: Temporarily log generated contexts to debug:
    \Log::debug('Generated context:', ['context' => $context]);
    
  • Check Annotations: Ensure @ApiResource and @ApiProperty are correctly applied to entities.

Extension Points

  1. 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']];
        }
    }
    
  2. Event Listeners: Hook into api_platform.jsonld.context_builder events (Symfony) or Laravel’s events to modify contexts.

  3. Hybrid Serialization: Combine with api-platform/core’s SerializerContextBuilder for mixed JSON/JSON-LD responses.

  4. Testing: Mock JsonLdContextBuilder in unit tests:

    $builder = $this->createMock(JsonLdContextBuilder::class);
    $builder->method('buildFromResourceClass')->willReturn(['@context' => []]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky