alcalyn/flush-on-kernel-terminate-bundle
EntityManager::flush() is intentionally deferred (e.g., for performance) but must eventually execute.doctrine/orm) differ fundamentally from Symfony2’s KernelTerminate event. The bundle’s listener logic would need to be rewritten to:
TerminateMiddleware or HttpKernel::terminate().EventDispatcher with Laravel’s Events or ServiceProvider bootstrapping.EntityManager methods, event system) may require adjustments.KernelEvents with Laravel’s middleware/events.doctrine/orm package).terminate middleware to flush manually.Illuminate\Http\Events\RequestHandled or custom events.Gedmo\Timestampable or custom listeners for post-save hooks.spatie/laravel-doctrine-orm) that already handle this?FlushOnKernelTerminateEvent) that cannot be replicated?KernelTerminate vs. Laravel’s middleware/events.Option 1: Custom Middleware
Replace the bundle’s listener with a Laravel middleware that hooks into terminate():
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Doctrine\ORM\EntityManagerInterface;
class FlushEntitiesMiddleware
{
public function __construct(private EntityManagerInterface $em) {}
public function terminate(Request $request, $next) {
$this->em->flush();
return $next($request);
}
}
Pros: Minimal effort, leverages existing Laravel patterns. Cons: Less granular control (flushes all pending entities, not just "deferred" ones).
Option 2: Event Listener
Use Laravel’s Events facade to trigger a flush after RequestHandled:
Event::listen(RequestHandled::class, function () {
app(EntityManagerInterface::class)->flush();
});
Pros: Clean separation of concerns. Cons: Same lack of granularity as middleware.
Option 3: Fork and Adapt Rewrite the bundle as a Laravel package with:
ServiceProvider to register a terminate middleware.Artisan uses a different lifecycle).preFlush, postFlush) interfering with the logic.EntityManager decorator to track "deferred" entities.flush() deferred to a job).EntityManager::flush() behavior changes.LifecycleEventArgs).symfony/symfony:2.x). These must be removed or replaced.deferFlush() method on EntityManager).| Scenario | Impact | Mitigation Strategy |
|---|---|---|
| Middleware fails to execute | Unflushed entities remain in memory, risking leaks. | Add retry logic or logging for failed flushes. |
| Doctrine ORM throws on flush | Request terminates abnormally, potentially corrupting state. | Wrap flush in a try-catch; log errors without crashing the response. |
| CLI/Queue contexts ignored | Deferred flushes don’t apply to non-HTTP requests. | Extend the solution to listen to ArtisanStarting or queue job events. |
| EntityManager not injected | Flush fails silently. | Use Laravel’s container binding to ensure EntityManager is always available |
How can I help you explore Laravel packages today?