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

Crud Api Bundle Laravel Package

arguv/crud-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require arguv/crud-api-bundle:dev-master
    

    Add to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    Arguv\CrudApiBundle\CrudApiBundle::class => ['all' => true],
    
  2. Routing: Add to config/routes.yaml:

    arguv_crud_api:
        resource: '@CrudApiBundle/Controller/'
        type: annotation
    
  3. First Use Case:

    • Create a Doctrine entity (e.g., src/Entity/Book.php).
    • Annotate it with #[ORM\Entity] and define fields (e.g., name, description).
    • Run:
      php bin/console doctrine:schema:update --force
      
    • Test endpoints:
      • GET /arguv/list → List all records.
      • POST /arguv/create → Create a new record (JSON payload).

Implementation Patterns

Workflows

  1. Entity-Centric Development:

    • Define entities with standard Doctrine annotations (#[ORM\Column], #[ORM\Id]).
    • Bundle auto-generates CRUD routes for each entity (e.g., Book/arguv/book/list).
  2. Request/Response Handling:

    • Input: Expects JSON payloads for create/update (e.g., {"name": "Smith", "description": "..."}).
    • Output: Returns JSON arrays (e.g., [{"name": "Smith", "id": 1}]).
    • Customize serialization with JMS Serializer or Symfony’s SerializerInterface.
  3. Integration with Services:

    • Extend bundle logic by injecting services into controllers (e.g., #[Autowired]).
    • Override default behavior via event listeners (e.g., kernel.event_listener).
  4. Pagination:

    • Add query parameters for pagination (e.g., ?page=1&limit=10) to list endpoints.
    • Modify CrudApiBundle/Controller/AbstractCrudController to support custom pagination logic.
  5. Validation:

    • Use Symfony’s Validator component to validate incoming data.
    • Example:
      use Symfony\Component\Validator\Constraints as Assert;
      
      #[ORM\Entity]
      class Book {
          #[Assert\NotBlank]
          #[ORM\Column]
          private string $name;
      }
      

Gotchas and Tips

Pitfalls

  1. Symfony Version Mismatch:

    • Bundle requires Symfony 3.4+ and Doctrine ORM 2.5+. Test locally before deploying to Symfony 4/5.
    • Fix: Use composer require symfony/framework-bundle:^3.4 if downgrading.
  2. Auto-Routing Overrides:

    • Bundle auto-generates routes for all entities. Conflicts may arise with existing routes.
    • Fix: Exclude specific entities by overriding the route loader or using route prefixes:
      arguv_crud_api_book:
          resource: '@CrudApiBundle/Controller/BookController'
          type: annotation
          prefix: /api/v1
      
  3. Missing Documentation:

    • No built-in API documentation (e.g., Swagger/OpenAPI). Manually document endpoints or integrate with NelmioApiDoc.
  4. Soft Deletes:

    • delete endpoint performs hard deletes by default. For soft deletes:
      • Extend AbstractCrudController and override deleteAction().
      • Use Doctrine lifecycle callbacks (preRemove).
  5. CORS Issues:

    • Bundle doesn’t handle CORS. Add middleware or configure Symfony’s cors bundle:
      # config/packages/nelmio_cors.yaml
      nelmio_cors:
          defaults:
              allow_origin: ["*"]
              allow_methods: ["GET", "POST", "PUT", "DELETE"]
      

Tips

  1. Custom Controllers:

    • Override default controllers by creating a custom one (e.g., src/Controller/CustomBookController) and extending AbstractCrudController:
      class CustomBookController extends AbstractCrudController {
          protected static string $entityClass = Book::class;
          // Override methods (e.g., createAction(), listAction())
      }
      
  2. Filtering/Sorting:

    • Add query parameters for filtering (e.g., ?name=Smith) or sorting (e.g., ?sort=-createdAt).
    • Modify listAction() in your custom controller to parse and apply filters:
      $queryBuilder = $this->getEntityManager()
          ->getRepository(self::$entityClass)
          ->createQueryBuilder('e');
      if ($name = $request->query->get('name')) {
          $queryBuilder->andWhere('e.name LIKE :name')->setParameter('name', "%$name%");
      }
      
  3. Testing:

    • Use Symfony’s WebTestCase to test endpoints:
      public function testCreateBook() {
          $client = static::createClient();
          $client->request('POST', '/arguv/book/create', [
              'json' => ['name' => 'Test', 'description' => 'Test Book']
          ]);
          $this->assertEquals(201, $client->getResponse()->getStatusCode());
      }
      
  4. Performance:

    • Disable bundle’s auto-routing for read-only entities to reduce overhead.
    • Use DTOs (Data Transfer Objects) for complex responses to avoid over-fetching.
  5. Extending with Events:

    • Listen to bundle events (e.g., crud.api.pre_create) to inject logic:
      // src/EventListener/CrudListener.php
      class CrudListener {
          public function onPreCreate(PreCreateEvent $event) {
              $data = $event->getData();
              $data['createdBy'] = $this->getUserId(); // Custom logic
              $event->setData($data);
          }
      }
      
      Register in services.yaml:
      services:
          App\EventListener\CrudListener:
              tags:
                  - { name: kernel.event_listener, event: crud.api.pre_create }
      
  6. Debugging:

    • Enable Symfony’s profiler to inspect requests/responses.
    • Check Doctrine logs for SQL queries:
      # config/packages/dev/doctrine.yaml
      doctrine:
          dbal:
              logging: true
              profiling: true
      
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