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

Base Rest Bundle Laravel Package

acseo/base-rest-bundle

Symfony bundle providing a base REST layer you can extend to expose your entities. Designed as a starting point for building REST APIs with reusable controllers/services; install via Composer and enable the bundle in your kernel.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require acseo/base-rest-bundle:dev-master
    

    Register the bundle in AppKernel.php:

    new ACSEO\BaseRestBundle\ACSEOBaseRestBundle(),
    
  2. First Use Case: Basic CRUD Endpoint

    • Extend ACSEO\BaseRestBundle\BaseRestController for your entity controller.
    • Annotate your entity with @ACSEO\BaseRestBundle\Annotation\Rest (if annotations are supported).
    • Example:
      use ACSEO\BaseRestBundle\BaseRestController;
      
      class PostController extends BaseRestController
      {
          protected $entityClass = 'App\Entity\Post';
      }
      
    • Define routes in config/routing.yml:
      acseo_base_rest:
          resource: "@ACSEOBaseRestBundle/Resources/config/routing.yml"
          prefix: /api
      
  3. Key Files to Review

    • src/ACSEO/BaseRestBundle/Resources/config/routing.yml (default routes)
    • src/ACSEO/BaseRestBundle/BaseRestController.php (base controller logic)
    • src/ACSEO/BaseRestBundle/Annotation/Rest.php (if annotations are used)

Implementation Patterns

1. Controller Extension Workflow

  • Base Controller: Extend BaseRestController and override:
    protected $entityClass; // Your entity FQCN
    protected $serializerGroups = ['default']; // Serializer groups
    
  • Custom Actions: Override methods like getEntity(), createEntity(), or updateEntity() for logic.
    public function updateEntity($data)
    {
        $entity = $this->getEntity();
        $entity->setCustomField($data['custom_field']);
        return $this->saveEntity($entity);
    }
    

2. Routing and API Structure

  • Default Routes: The bundle provides /api/{entity} routes (e.g., /api/posts).
  • Custom Routes: Extend routing.yml or use annotations:
    acseo_base_rest_post:
        path: /api/v1/posts
        methods: [GET, POST]
        defaults: { _controller: App\Controller\PostController::index }
    

3. Serialization and Validation

  • Groups: Use Symfony Serializer groups (e.g., ['read', 'write']) in $serializerGroups.
  • Validation: Leverage Symfony Validator via $this->validator in the base controller.
    public function createEntity($data)
    {
        $entity = new $this->entityClass();
        $errors = $this->validator->validate($entity, ['create']);
        if (count($errors)) { throw new \RuntimeException((string) $errors); }
        // ...
    }
    

4. Integration with Doctrine

  • Repository: Access the entity repository via $this->getRepository().
  • DQL: Use Doctrine Query Language in custom methods:
    public function customAction()
    {
        $posts = $this->getRepository()->createQueryBuilder('p')
            ->where('p.published = :published')
            ->setParameter('published', true)
            ->getQuery()
            ->getResult();
        return $this->serialize($posts);
    }
    

5. Event Listeners/Subscribers

  • Pre/Post Actions: Extend the bundle by adding listeners to events like:
    • acseo_base_rest.pre_create
    • acseo_base_rest.post_update
  • Example subscriber:
    class PostSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'acseo_base_rest.pre_create' => 'onPreCreate',
            ];
        }
    
        public function onPreCreate(PreCreateEvent $event)
        {
            $event->setData('created_by', 'system');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Bundle Maturity:

    • The bundle is in early development (dev-master). Expect breaking changes.
    • Tip: Fork the repo and extend it for production use.
  2. Annotation Support:

    • The @Rest annotation is mentioned but may not be fully implemented.
    • Workaround: Stick to controller extension for now.
  3. Routing Conflicts:

    • Default routes (/api/{entity}) may clash with existing routes.
    • Fix: Override routing.yml or use custom route namespaces.
  4. Serialization Issues:

    • Serializer groups must match your entity’s @Groups annotations.
    • Debug: Use var_dump($this->serializer->getGroups()) to verify.
  5. Doctrine Integration:

    • Assumes Doctrine ORM. For Doctrine ODM or other DBALs, extend BaseRestController heavily.
    • Tip: Override getEntityManager() if needed.

Debugging Tips

  1. Enable Debug Mode:

    // config/packages/dev/acseo_base_rest.yaml
    acseo_base_rest:
        debug: true
    
    • Logs actions to var/log/dev.log.
  2. Event Debugging:

    • Dump events in subscribers:
      public function onPreCreate(PreCreateEvent $event)
      {
          file_put_contents('debug.log', print_r($event->getData(), true));
      }
      
  3. Controller Overrides:

    • Use parent::method() to call base logic when extending:
      public function createEntity($data)
      {
          $data['meta'] = ['timestamp' => time()];
          return parent::createEntity($data);
      }
      

Extension Points

  1. Custom Serializers:

    • Override getSerializer() in your controller to use custom serializers:
      protected function getSerializer()
      {
          return $this->container->get('serializer.custom');
      }
      
  2. Authentication/Authorization:

    • Extend BaseRestController to add security:
      public function index()
      {
          $this->denyAccessUnlessGranted('ROLE_API_USER');
          return parent::index();
      }
      
  3. API Versioning:

    • Use Symfony’s version parameter or route prefixes:
      acseo_base_rest_v1:
          resource: "@ACSEOBaseRestBundle/Resources/config/routing.yml"
          prefix: /api/v1
      
  4. Testing:

    • Mock the base controller in PHPUnit:
      $controller = $this->getMockBuilder(BaseRestController::class)
          ->setMethods(['getEntityManager'])
          ->getMock();
      $controller->method('getEntityManager')->willReturn($entityManager);
      

```markdown
### **Configuration Quirks**
1. **Missing `config/packages/acseo_base_rest.yaml`**:
   - The bundle may not create this file automatically. Create it manually:
     ```yaml
     acseo_base_rest:
         default_entity: App\Entity\Post
         serializer_groups: ['default']
     ```
   - Access config in controllers via `$this->container->getParameter('acseo_base_rest.default_entity')`.

2. **Entity Class Validation**:
   - Ensure `$entityClass` in your controller is a fully qualified class name (e.g., `App\Entity\Post`), not a short name.

3. **CORS Issues**:
   - The bundle doesn’t include CORS headers by default. Add middleware like `NelmioCorsBundle` if needed.

### **Performance Tips**
1. **Pagination**:
   - Implement custom pagination in `index()`:
     ```php
     use Knp\Component\Pager\PaginatorInterface;

     public function index(PaginatorInterface $paginator)
     {
         $data = $paginator->paginate(
             $this->getRepository()->createQueryBuilder('e')->getQuery(),
             $this->get('request')->query->getInt('page', 1),
             20
         );
         return $this->serialize($data);
     }
     ```

2. **Caching**:
   - Cache serialized responses in `BaseRestController`:
     ```php
     use Symfony\Component\HttpFoundation\Response;

     public function index()
     {
         $cacheKey = 'api_posts_' . $this->getRequest()->getClientIp();
         if ($cached = $this->cache->get($cacheKey)) {
             return new Response($cached);
         }
         $data = parent::index();
         $this->cache->set($cacheKey, $data->getContent(), 300);
         return $data;
     }
     ```
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