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

Rest Bundle Laravel Package

desksheet/rest-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require desksheet/rest-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Desksheet\RestBundle\DesksheetRestBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Basic CRUD Endpoint

    • Create a resource class (e.g., src/Entity/Book.php):
      namespace App\Entity;
      use Desksheet\RestBundle\Annotation\Rest;
      #[Rest]
      class Book {}
      
    • Generate routes automatically via:
      php bin/console desksheet:rest:generate
      
    • Test endpoints at /api/books (GET, POST, PUT, DELETE).
  3. Key Files to Review

    • config/packages/desksheet_rest.yaml (default config).
    • src/Entity/ (annotated entities for auto-routing).
    • src/Controller/ (custom logic overrides).

Implementation Patterns

1. Annotation-Driven Routing

  • Default Behavior: Annotate entities with @Rest to auto-generate RESTful routes (e.g., GET /api/{entity}).
    #[Rest(
        routePrefix: 'api/v1',
        collectionOperations: ['get', 'post'],
        itemOperations: ['get', 'put', 'delete']
    )]
    class Product {}
    
  • Customization: Override operations in config/packages/desksheet_rest.yaml:
    desksheet_rest:
        resources:
            App\Entity\Product:
                collection:
                    - { method: 'GET', path: '/products' }
                    - { method: 'POST', path: '/products', name: 'create_product' }
                item:
                    - { method: 'GET', path: '/products/{id}' }
    

2. Serialization Groups

  • Use Symfony’s #[Groups] for field filtering:
    use Symfony\Component\Serializer\Annotation\Groups;
    
    class User {
        #[Groups(['user:read'])]
        private string $name;
    
        #[Groups(['user:write'])]
        private string $email;
    }
    
  • Configure in config/packages/desksheet_rest.yaml:
    desksheet_rest:
        serialization:
            groups: ['user:read', 'user:write']
    

3. Event-Driven Extensions

  • Listen to desksheet.rest.pre_read/post_write events for pre/post-processing:
    // src/EventListener/CustomListener.php
    namespace App\EventListener;
    use Desksheet\RestBundle\Event\RestEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CustomListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                RestEvent::PRE_READ => 'onPreRead',
                RestEvent::POST_WRITE => 'onPostWrite',
            ];
        }
    
        public function onPreRead(RestEvent $event) {
            $event->getData()->set('custom_field', 'value');
        }
    }
    

4. Validation Integration

  • Use Symfony Validator with annotations:
    use Symfony\Component\Validator\Constraints as Assert;
    
    class Order {
        #[Assert\NotBlank]
        #[Assert\Positive]
        private int $quantity;
    }
    
  • Auto-validate on POST/PUT via bundle config:
    desksheet_rest:
        validation: true
    

5. Pagination

  • Enable KnpPaginator (recommended) or use bundle’s built-in:
    desksheet_rest:
        pagination:
            enabled: true
            items_per_page: 20
    

Gotchas and Tips

Pitfalls

  1. Route Conflicts

    • Avoid naming collisions with existing routes. Use routePrefix in annotations or desksheet_rest.yaml to namespace routes.
    • Debug with:
      php bin/console debug:router | grep desksheet
      
  2. Serialization Mismatches

    • Ensure entity properties are public or have getters/setters. The bundle uses Symfony’s ObjectNormalizer.
    • Test serialization with:
      php bin/console debug:serializer App\Entity\Book
      
  3. Event Dispatching Order

    • PRE_READ fires before data is fetched; POST_READ fires after. Modify data in PRE_READ to affect responses.
    • Example: Add computed fields in PRE_READ.
  4. Caching Headers

    • The bundle doesn’t auto-generate ETag/Last-Modified. Add manually in listeners or controllers:
      $event->getResponse()->setETag(md5($data));
      

Debugging Tips

  • Enable Verbose Logging:
    # config/packages/dev/desksheet_rest.yaml
    desksheet_rest:
        debug: true
    
  • Check Generated Routes:
    php bin/console debug:router | grep desksheet
    
  • Validate Entities:
    php bin/console debug:validator App\Entity\Book
    

Extension Points

  1. Custom Controllers

    • Override default behavior by creating a controller and annotating it with @RestController:
      #[RestController]
      class CustomBookController extends AbstractRestController {
          public function getCollection(Options $options) {
              // Custom logic
          }
      }
      
  2. Dynamic Route Parameters

    • Use #[Rest(routeName: 'custom_route')] to bind to existing routes or custom logic.
  3. API Platform Integration

    • Combine with API Platform for GraphQL/REST hybrid APIs. Disable bundle’s auto-routing and use API Platform’s annotations.
  4. Testing

    • Use Desksheet\RestBundle\Test\RestTestCase for functional tests:
      use Desksheet\RestBundle\Test\RestTestCase;
      
      class BookTest extends RestTestCase {
          public function testGetBooks() {
              $this->client->request('GET', '/api/books');
              $this->assertResponseIsSuccessful();
          }
      }
      

Performance Quirks

  • Eager-Loading: The bundle uses Doctrine’s Hydrator by default. For complex queries, add #[ORM\QueryBuilder] to entities or use DQL in PRE_READ events.
  • Memory Usage: Avoid loading large collections without pagination. Use #[ORM\QueryBuilder] to limit results:
    #[ORM\QueryBuilder(
        class: Book::class,
        method: 'createPaginatedQueryBuilder',
        options: ['limit' => 50]
    )]
    class Book {}
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui