Weave 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

Flush On Kernel Terminate Bundle Laravel Package

alcalyn/flush-on-kernel-terminate-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require alcalyn/flush-on-kernel-terminate:1.x
    
  2. Register the Bundle: Add to app/AppKernel.php:
    new Alcalyn\FlushOnKernelTerminateBundle\AlcalynFlushOnKernelTerminateBundle(),
    
  3. First Use Case: Use this bundle in scenarios where you intentionally defer flush() calls (e.g., bulk operations, API batch processing) but need guarantees that pending changes persist before the request ends. No additional code changes are required—just rely on the bundle’s automatic listener.

Implementation Patterns

Workflow Integration

  1. Deferred Flush Scenarios:

    • Bulk Operations: Process 100+ entities in a loop without flushing mid-request.
      foreach ($entities as $entity) {
          $entityManager->persist($entity);
          // No flush() here
      }
      // Bundle flushes all pending changes after response.
      
    • API Batch Endpoints: Handle large payloads efficiently (e.g., /api/import).
    • Long-Running Tasks: Useful in CLI commands or background jobs where flush() is omitted for performance.
  2. Conditional Flushing:

    • Explicit Flush Override: Force immediate flush via $entityManager->flush() if needed (e.g., for critical data).
    • Transactional Boundaries: Pair with @Transactional (Doctrine) to ensure atomicity where required.
  3. Event-Driven Extensions:

    • Custom Logic: Extend the bundle by subscribing to kernel.terminate in your own bundle:
      $eventDispatcher->addListener(KernelEvents::TERMINATE, function () use ($em) {
          if ($em->isOpen() && $em->getUnitOfWork()->hasScheduledEntityInsertions()) {
              $em->flush();
          }
      });
      

Performance Considerations

  • Benchmark: Compare response times with/without the bundle for deferred-flush-heavy endpoints.
  • Database Load: Monitor server metrics during peak traffic to avoid unintended flush spikes.

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies:

    • The package targets Symfony 2.x (last release: 2014). Test thoroughly in modern Laravel (Symfony 5+) environments.
    • Workaround: Use a compatibility layer (e.g., symfony/event-dispatcher) if migrating to newer Symfony versions.
  2. EntityManager State:

    • Closed Connections: If the EntityManager is closed (e.g., after request end), the bundle silently fails. Ensure $em->isOpen() before flushing in custom logic.
    • Detached Entities: Flushing detached entities may cause EntityManager#flush() to throw exceptions. Validate state pre-flush.
  3. Race Conditions:

    • Concurrent Requests: The bundle flushes all pending changes per request. Avoid mixing deferred and immediate flushes in multi-threaded contexts (e.g., queues).

Debugging

  • Log Flushes: Add a listener to log flush operations:
    $dispatcher->addListener(KernelEvents::TERMINATE, function () {
        \Log::debug('FlushOnKernelTerminateBundle triggered flush.');
    });
    
  • Check UnitOfWork: Verify pending changes with:
    $uow = $em->getUnitOfWork();
    \Log::debug('Pending inserts:', $uow->getScheduledEntityInsertions());
    

Extension Points

  1. Custom Flush Conditions:
    • Override the default behavior by replacing the bundle’s listener:
      $dispatcher->removeListener(KernelEvents::TERMINATE, [$bundle, 'onKernelTerminate']);
      $dispatcher->addListener(KernelEvents::TERMINATE, [$this, 'customFlushLogic']);
      
  2. Entity Filtering:
    • Filter entities to flush (e.g., skip certain classes):
      $em->getUnitOfWork()->getScheduledEntityInsertions()
          ->filter(fn ($entity) => !$entity instanceof SkippableEntity);
      
  3. Post-Flush Actions:
    • Chain post-flush logic (e.g., notifications):
      $dispatcher->addListener('flush.post', function () {
          // Send webhook after flush.
      });
      

Configuration Quirks

  • No Config File: The bundle has no configurable options—behavior is fixed (flush all pending changes).
  • Doctrine Version: Tested with Doctrine ORM 2.x. For Laravel’s Eloquent, consider alternatives like Model::flush() or queue-based persistence.
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.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin