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

Hateoas Bundle Laravel Package

willdurand/hateoas-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require willdurand/hateoas-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        WillDurand\Hateoas\Bundle\HateoasBundle::class => ['all' => true],
    ];
    
  2. First Use Case:

    • Generate a HATEOAS representation for a resource (e.g., API response):
      use WillDurand\Hateoas\Representation\CollectionRepresentation;
      use WillDurand\Hateoas\Representation\PaginatedRepresentation;
      use WillDurand\Hateoas\Representation\RepresentationInterface;
      
      // Example: Wrap a collection with links
      $representation = new CollectionRepresentation($items, [
          'self' => ['route' => 'api_items', 'routeParameters' => ['page' => 1]],
          'next' => ['route' => 'api_items', 'routeParameters' => ['page' => 2]],
      ]);
      
  3. Where to Look First:

    • Documentation
    • src/Representation/ for core classes (RepresentationInterface, CollectionRepresentation, etc.).
    • src/Builder/ for dynamic link generation.

Implementation Patterns

Core Workflows

  1. Embedding Links in Responses:

    • Use RepresentationInterface to attach links to data:
      $representation = new Representation($data, [
          'self' => ['route' => 'api_show', 'routeParameters' => ['id' => $id]],
          'edit' => ['route' => 'api_edit', 'routeParameters' => ['id' => $id]],
      ]);
      return $this->json($representation);
      
  2. Pagination with HATEOAS:

    • Leverage PaginatedRepresentation for paginated APIs:
      $paginated = new PaginatedRepresentation(
          $items,
          ['self' => ['route' => 'api_items', 'routeParameters' => ['page' => 1]]],
          $totalItems,
          $pageSize
      );
      
  3. Dynamic Link Generation:

    • Use Builder\BuilderInterface to generate links programmatically:
      $builder = $this->get('hateoas.builder');
      $link = $builder->uriFor('api_show', ['id' => $id]);
      
  4. Embedding Sub-Representations:

    • Nest representations for hierarchical data:
      $user = new Representation($userData, ['self' => $selfLink]);
      $representation = new Representation($data, [
          'self' => $selfLink,
          'user' => $user,
      ]);
      
  5. Integration with Symfony Serializers:

    • Use the Hateoas\Serializer\HateoasSerializer to normalize representations:
      # config/packages/hateoas.yaml
      hateoas:
          serializer:
              enabled: true
      

Integration Tips

  • API Platform: Works seamlessly with API Platform for automatic HATEOAS generation.
  • FOSRestBundle: Combine with FOSRest for RESTful APIs:
    # config/packages/fos_rest.yaml
    fos_rest:
        view:
            formats:
                json: true
            mime_types:
                json: ['application/json', 'application/hal+json']
    
  • Custom Link Providers: Extend LinkProviderInterface for domain-specific links.

Gotchas and Tips

Pitfalls

  1. Route Resolution:

    • Ensure routes are properly defined and accessible from the controller. Undefined routes will throw exceptions.
    • Fix: Use absolute paths or verify route names in routeParameters.
  2. Circular References:

    • Deeply nested representations may cause infinite loops during serialization.
    • Fix: Use Hateoas\Serializer\HateoasSerializer with ignore_circular_references: true in config.
  3. Overhead in Simple APIs:

    • Adding HATEOAS to every endpoint may be unnecessary for simple CRUD APIs.
    • Tip: Use selectively (e.g., only for complex resources or collections).
  4. Deprecated Methods:

    • Some older versions use deprecated methods (e.g., addLink instead of setLink).
    • Tip: Check the changelog for breaking changes.

Debugging

  • Enable Debug Mode:

    # config/packages/hateoas.yaml
    hateoas:
        debug: true
    

    Logs link generation and serialization issues.

  • Validate Representations: Use RepresentationInterface::getLinks() to inspect generated links:

    $links = $representation->getLinks();
    dump($links);
    

Extension Points

  1. Custom Representation Classes: Extend Representation for domain-specific logic:

    class PostRepresentation extends Representation {
        public function __construct($data, array $links = []) {
            parent::__construct($data, $links);
            $this->addLink('comments', ['route' => 'api_post_comments', 'routeParameters' => ['id' => $data['id']]]);
        }
    }
    
  2. Link Providers: Implement LinkProviderInterface for dynamic links:

    class UserLinkProvider implements LinkProviderInterface {
        public function getLinks($resource) {
            return [
                'profile' => ['route' => 'api_user_profile', 'routeParameters' => ['id' => $resource['id']]],
            ];
        }
    }
    

    Register in services:

    services:
        App\LinkProvider\UserLinkProvider:
            tags: [hateoas.link_provider]
    
  3. Serializer Groups: Use Symfony’s serializer groups to control which fields/links are included:

    $representation = new Representation($data, $links, ['groups' => ['api']]);
    

Config Quirks

  • Disable HATEOAS Globally:

    hateoas:
        enabled: false
    

    Useful for non-RESTful parts of the app.

  • Custom Link Templates: Override default link templates in config/packages/hateoas.yaml:

    hateoas:
        link_templates:
            self: 'api_{resource}_self'
            next: 'api_{resource}_next'
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware