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

Restful Bundle Laravel Package

brightmarch/restful-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the bundle to composer.json:

    "brightmarch/restful-bundle": "^1.0"
    

    Run composer update and register the bundle in AppKernel.php:

    new Brightmarch\Bundle\RestfulBundle\BrightmarchRestfulBundle(),
    
  2. First Resource Create a controller extending RestfulController:

    namespace AppBundle\Controller;
    use Brightmarch\Bundle\RestfulBundle\Controller\RestfulController;
    
    class PostsController extends RestfulController
    {
        // Define your resource methods below
    }
    
  3. Routing Configure routes in routing.yml:

    app_posts:
        resource: "@AppBundle/Controller/PostsController.php"
        type:     restful
        prefix:   /api/posts
    
  4. First Action Implement a basic indexAction to list resources:

    public function indexAction()
    {
        return $this->getList(['id', 'title'], 'AppBundle:Post');
    }
    

Where to Look First

  • Bundle Docs: Check the README for core concepts.
  • Controller Base: Review RestfulController methods (e.g., getList(), getItem(), createItem()).
  • Exceptions: Familiarize yourself with built-in exceptions like HttpUnauthorizedException.

Implementation Patterns

Core Workflows

  1. CRUD Operations Leverage built-in methods for standard REST actions:

    // List resources (GET /posts)
    public function indexAction() {
        return $this->getList(['id', 'title'], 'AppBundle:Post');
    }
    
    // Get single resource (GET /posts/{id})
    public function getAction($id) {
        return $this->getItem($id, 'AppBundle:Post');
    }
    
    // Create resource (POST /posts)
    public function postAction() {
        return $this->createItem('AppBundle:Post');
    }
    
    // Update resource (PUT/PATCH /posts/{id})
    public function putAction($id) {
        return $this->updateItem($id, 'AppBundle:Post');
    }
    
    // Delete resource (DELETE /posts/{id})
    public function deleteAction($id) {
        return $this->deleteItem($id, 'AppBundle:Post');
    }
    
  2. Custom Logic Override methods to inject business logic:

    public function getItem($id, $entity) {
        $item = parent::getItem($id, $entity);
        // Add custom logic (e.g., permissions, transformations)
        return $item;
    }
    
  3. Validation Use Symfony’s validator with $this->get('validator'):

    public function postAction() {
        $data = $this->getRequest()->request->all();
        $errors = $this->get('validator')->validate($data);
        if (count($errors)) {
            throw new HttpBadRequestException('Validation failed');
        }
        return $this->createItem('AppBundle:Post');
    }
    
  4. Pagination Configure pagination in getList():

    public function indexAction() {
        return $this->getList(
            ['id', 'title'],
            'AppBundle:Post',
            ['limit' => 10, 'offset' => 0]
        );
    }
    

Integration Tips

  • Doctrine ORM: Works seamlessly with Doctrine entities. Ensure your entity has an id field.
  • FOSRestBundle: Combine with FOSRestBundle for advanced features like format negotiation.
  • API Platform: Use as a lightweight alternative for simple APIs before migrating to API Platform.
  • Testing: Mock RestfulController in PHPUnit tests:
    $controller = $this->getMockBuilder('AppBundle\Controller\PostsController')
        ->setMethods(['getItem'])
        ->getMock();
    

Gotchas and Tips

Pitfalls

  1. Entity Not Found

    • Issue: getItem() throws HttpNotFoundException if the entity doesn’t exist.
    • Fix: Handle gracefully or override the method to return a custom response:
      public function getItem($id, $entity) {
          try {
              return parent::getItem($id, $entity);
          } catch (HttpNotFoundException $e) {
              return $this->json(['error' => 'Resource not found'], 404);
          }
      }
      
  2. CSRF Protection

    • Issue: POST/PUT/DELETE actions may fail due to CSRF tokens in Symfony’s default config.
    • Fix: Disable CSRF for API routes in config.yml:
      framework:
          csrf_protection:
              enabled: false
      
  3. Route Overrides

    • Issue: Custom routes may conflict with the bundle’s restful type.
    • Fix: Use explicit route names or extend the bundle’s router.
  4. Deprecated Methods

    • Issue: Some methods (e.g., get()) may be deprecated in newer Symfony versions.
    • Fix: Use dependency injection ($this->get('service')) instead of $this->get().

Debugging Tips

  • Enable Debug Mode: Set APP_DEBUG=true in .env to see detailed error messages.
  • Log Requests: Add logging in overridden methods:
    public function postAction() {
        $this->get('logger')->info('POST request data:', $this->getRequest()->request->all());
        return parent::postAction();
    }
    
  • Check Headers: Use dump($this->getRequest()->headers) to inspect incoming headers.

Extension Points

  1. Custom Responses Override createResponse() to modify JSON structure:

    protected function createResponse($data, $status = 200, array $headers = []) {
        $data['custom_field'] = 'value';
        return parent::createResponse($data, $status, $headers);
    }
    
  2. Authentication Integrate with security bundles (e.g., LexikJWTAuthenticationBundle):

    public function getAction($id) {
        if (!$this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
            throw new HttpUnauthorizedException('Authentication required');
        }
        return parent::getAction($id);
    }
    
  3. Event Listeners Attach listeners to modify behavior:

    // services.yml
    services:
        app.post_listener:
            class: AppBundle\EventListener\PostListener
            tags:
                - { name: kernel.event_listener, event: restful.pre_list, method: onPreList }
    
  4. Serialization Use JMS Serializer or Symfony’s serializer to customize output:

    public function indexAction() {
        $list = $this->getList(['id', 'title'], 'AppBundle:Post');
        $serializer = $this->get('jms_serializer');
        return new JsonResponse($serializer->serialize($list, 'json'));
    }
    

Configuration Quirks

  • Bundle Order: Ensure BrightmarchRestfulBundle is loaded after FrameworkBundle in AppKernel.php.
  • Route Priority: The restful route type has low priority by default. Use _priority: 10 in routing.yml if needed.
  • Entity Manager: The bundle assumes a single Doctrine\ORM\EntityManager. For multi-DB setups, inject the correct EM:
    $this->get('doctrine.orm.entity_manager')->getRepository('AppBundle:Post');
    
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