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

Http Kernel Laravel Package

symfony/http-kernel

Symfony HttpKernel provides a structured request-to-response workflow built on EventDispatcher. It powers full-stack frameworks, micro-frameworks, and advanced CMSs by handling kernel events, controller resolution, and response generation in a flexible pipeline.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/http-kernel
    

    Laravel already includes this component under the hood, so no explicit installation is needed unless extending functionality.

  2. Core Concepts:

    • The HttpKernel converts a Request into a Response via a structured pipeline.
    • Key classes: HttpKernelInterface, Kernel, Request, Response, EventDispatcher.
  3. First Use Case:

    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpKernel\HttpKernelInterface;
    
    $request = Request::createFromGlobals();
    $kernel = new \App\Http\Kernel(); // Laravel's Kernel extends Symfony's Kernel
    $response = $kernel->handle($request);
    $response->send();
    
  4. Where to Look First:


Implementation Patterns

Core Workflows

  1. Request Handling Pipeline:

    // Laravel's Kernel extends Symfony's Kernel and implements HttpKernelInterface
    $response = $kernel->handle(
        $request,
        HttpKernelInterface::MAIN_REQUEST, // or SUB_REQUEST
        $catch = true // whether to catch exceptions
    );
    
    • MAIN_REQUEST: Full request lifecycle (middleware, controller, response).
    • SUB_REQUEST: For fragments (e.g., @include in Blade).
  2. Middleware Integration: Laravel’s middleware leverages Symfony’s EventDispatcher:

    // In Kernel.php
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        // ...
    ];
    
    • Each middleware is a TerminableMiddlewareInterface or MiddlewareInterface.
  3. Event-Driven Extensions:

    // Listen to kernel events (e.g., request/response lifecycle)
    $dispatcher->addListener(KernelEvents::REQUEST, function (KernelEvent $event) {
        $request = $event->getRequest();
        // Modify request or add data
    });
    
  4. Sub-Requests for Fragments:

    // Example: Rendering a partial via a sub-request
    $subRequest = $request->duplicate(
        null,
        null,
        ['_route' => 'partial.route']
    );
    $fragment = $kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    
  5. Custom Kernel for CLI/Non-HTTP:

    // For non-HTTP contexts (e.g., CLI commands)
    $kernel = new class extends Kernel {
        public function boot() { /* ... */ }
        public function handle($request, $type = self::MAIN_REQUEST, $catch = true) { /* ... */ }
    };
    

Integration Tips

  • Leverage Laravel’s Built-in Kernel: Extend App\Http\Kernel instead of reinventing the wheel. Override methods like:
    public function handle($request, $type = self::MAIN_REQUEST, $catch = true)
    
  • Use HttpCache for Performance:
    use Symfony\Component\HttpKernel\HttpCache\HttpCache;
    
    $cache = new HttpCache($kernel, $cacheDir);
    $response = $cache->handle($request);
    
  • Debugging with HttpKernelBrowser:
    use Symfony\Component\HttpKernel\KernelInterface;
    use Symfony\Component\HttpKernel\HttpKernelBrowser;
    
    $client = new HttpKernelBrowser($kernel);
    $client->request('GET', '/');
    

Gotchas and Tips

Pitfalls

  1. Locale Handling:

    • Symfony’s HttpKernel resets the router locale to the default after handling a request. If you need to preserve it (e.g., for multi-language APIs), manually reset it:
      $router->setDefaultLocale($originalLocale);
      
  2. HEAD Requests and Security:

    • CVE-2026-45075: HEAD requests bypassed method filters (e.g., #[IsGranted]). Ensure your security logic accounts for this:
      // In a controller/middleware
      if ($request->isMethod('HEAD')) {
          // Handle HEAD-specific logic
      }
      
  3. Variadic Arguments:

    • Invalid # references in controller arguments (e.g., #invalid) can cause errors. Validate early:
      if (str_contains($argument, '#') && !preg_match('/#\w+$/', $argument)) {
          throw new \InvalidArgumentException('Invalid argument reference');
      }
      
  4. Enum Handling:

    • Backed enums in RequestPayloadValueResolver may fail silently. Explicitly handle invalid values:
      try {
          $enumValue = MyEnum::from($request->request->get('field'));
      } catch (\ValueError $e) {
          $enumValue = MyEnum::DEFAULT;
      }
      
  5. HttpCache in Worker Mode:

    • If using HttpCache with workers (e.g., Symfony Cloud), ensure the cache directory is shared:
      # config/packages/http_cache.yaml
      framework:
          http_cache:
              cache_dir: '%kernel.project_dir%/var/cache/http_cache'
      

Debugging Tips

  1. Enable Verbose Logging:

    $dispatcher->addListener(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) {
        \Log::error('Kernel Exception', [
            'exception' => $event->getThrowable(),
            'request' => $event->getRequest()->query->all(),
        ]);
    });
    
  2. Inspect Request/Response:

    // Dump request attributes
    \Symfony\Component\VarDumper\Caster\Caster::setCasters([
        new \Symfony\Component\HttpFoundation\RequestCaster(),
    ]);
    dump($request);
    
    // Dump response
    dump($response->getContent());
    
  3. Check for Deprecated Methods:

    • Symfony 8+ deprecates Kernel::VERSION. Use KernelInterface::VERSION instead.

Extension Points

  1. Custom Event Listeners:

    // Listen to kernel.finish_request
    $dispatcher->addListener(KernelEvents::FINISH_REQUEST, function (FinishRequestEvent $event) {
        $event->getResponse()->headers->set('X-Custom-Header', 'value');
    });
    
  2. Override Kernel Bootstrapping:

    // In a custom Kernel class
    public function boot()
    {
        parent::boot();
        // Add custom boot logic (e.g., register services)
    }
    
  3. Modify Request/Response Globally:

    // Add a global middleware to modify requests
    $dispatcher->addListener(KernelEvents::REQUEST, function (KernelEvent $event) {
        $event->setRequest($event->getRequest()->withHeader('X-Processed', 'true'));
    });
    
  4. Handle Exceptions:

    $dispatcher->addListener(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) {
        if ($event->getThrowable() instanceof \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface) {
            return;
        }
        $event->setResponse(new Response('Custom error', 500));
    });
    
  5. Sub-Request Caching:

    • Cache sub-requests (e.g., partials) using HttpCache:
      $cache = new HttpCache($kernel, $cacheDir);
      $fragment = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle