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

Runtime Laravel Package

symfony/runtime

Symfony Runtime decouples PHP applications from global state by centralizing bootstrapping and execution in a runtime layer. It enables flexible entry points, better testability, and smoother integration with different environments and frameworks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require symfony/runtime
    
  2. Wrap your Laravel index.php (HTTP entry point):
    use Symfony\Component\Runtime\Runner;
    use App\Kernel;
    
    return Runner::run(new Kernel(), $_SERVER['APP_RUNTIME'] ?? 'http');
    
  3. Update artisan (CLI entry point, artisan file):
    use Symfony\Component\Runtime\Runner;
    use App\Kernel;
    
    return Runner::run(new Kernel(), 'cli');
    

First Use Case: Isolate Global State

Replace direct $_SERVER/$_ENV access in middleware or services with dependency-injected alternatives:

// Before (global state)
if ($_SERVER['HTTP_USER_AGENT'] === 'curl') { ... }

// After (testable, runtime-aware)
public function __invoke(Request $request) {
    if ($request->headers->has('User-Agent: curl')) { ... }
}

Key Files to Modify

  • index.php (HTTP)
  • artisan (CLI)
  • .env (add APP_RUNTIME=http|cli|worker if needed)

Implementation Patterns

1. Runtime-Aware Bootstrapping

Workflow: Use APP_RUNTIME env var to switch between HTTP, CLI, or worker modes.

// config/runtime.php
return [
    'default' => env('APP_RUNTIME', 'http'),
    'runtimes' => [
        'http' => App\Runtime\HttpRuntime::class,
        'cli' => App\Runtime\CliRuntime::class,
        'worker' => App\Runtime\WorkerRuntime::class,
    ],
];

Integration Tip: Extend Symfony\Component\Runtime\RunnerInterface for custom runtimes (e.g., RoadRunner workers).

2. Dependency Injection

Pattern: Replace global state with injected services.

// Before
$host = $_SERVER['HTTP_HOST'];

// After (in a service)
public function __construct(private Request $request) {}

public function getHost(): string {
    return $this->request->getHost();
}

Laravel-Specific: Use Laravel’s container to bind runtime-specific services:

// app/Providers/AppServiceProvider.php
public function register() {
    $this->app->bind(\Symfony\Component\HttpFoundation\Request::class, function () {
        return Request::createFromGlobals();
    });
}

3. Environment Isolation

Use Case: Load .env files per runtime (e.g., .env.worker).

// In your runtime class
use Symfony\Component\Runtime\SymfonyRuntime;

class WorkerRuntime extends SymfonyRuntime {
    protected function getEnv(): array {
        return array_merge(
            parent::getEnv(),
            $_ENV + ['APP_RUNTIME' => 'worker']
        );
    }
}

4. FrankenPHP Optimization

Pattern: Auto-detect FrankenPHP’s worker mode.

// No config needed—Symfony Runtime auto-detects FrankenPHP via $_SERVER.

Tip: Set APP_RUNTIME=frankenphp in .env for explicit control.

5. Command-Line Integration

Workflow: Use Runner::run() for CLI commands.

// In artisan
return Runner::run(new Kernel(), 'cli', [
    'command' => 'migrate',
]);

Gotchas and Tips

Pitfalls

  1. Legacy Middleware:

    • Middleware using $_SERVER directly will break. Solution: Refactor to use Request objects or wrap in Runner.
    • Example fix:
      // Before (broken)
      public function handle($request, Closure $next) {
          if ($_SERVER['HTTP_X_API_KEY']) { ... }
      }
      
      // After (fixed)
      public function handle(Request $request, Closure $next) {
          if ($request->headers->has('X-API-KEY')) { ... }
      }
      
  2. Circular Dependencies:

    • Avoid injecting Runner into services that are resolved during bootstrapping. Solution: Use lazy loading or factory methods.
  3. PHP Version Mismatch:

    • Symfony Runtime v8.x requires PHP 8.4+. Solution: Use v7.x for older PHP versions.
  4. Custom Runtimes:

    • Extending SymfonyRuntime requires overriding getEnv() and getArguments(). Tip: Start with a minimal implementation:
      class CustomRuntime extends SymfonyRuntime {
          protected function getEnv(): array {
              return $_ENV + ['CUSTOM_VAR' => 'value'];
          }
      }
      

Debugging Tips

  1. Check Runtime Class:

    // Debug current runtime
    dump($_SERVER['APP_RUNTIME'] ?? 'default');
    
  2. Environment Variables:

    • Use Runtime::getEnv() to inspect loaded env vars:
      dump(SymfonyRuntime::getEnv());
      
  3. Worker Mode Issues:

    • FrankenPHP workers may need explicit runtime detection:
      if (php_sapi_name() === 'frankenphp-worker') {
          $_SERVER['APP_RUNTIME'] = 'frankenphp';
      }
      

Extension Points

  1. Custom Runtime Classes:

    • Extend Symfony\Component\Runtime\SymfonyRuntime for specialized behaviors (e.g., custom env loading).
  2. Runtime-Specific Config:

    • Load config per runtime using Runtime::getEnv():
      $config = [
          'timeout' => $_ENV['HTTP_TIMEOUT'] ?? 30,
          'worker_timeout' => $_ENV['WORKER_TIMEOUT'] ?? 60,
      ];
      
  3. Error Handling:

    • Override handleException() in custom runtimes:
      class CustomRuntime extends SymfonyRuntime {
          protected function handleException(Throwable $exception): void {
              // Custom logging/handling
              parent::handleException($exception);
          }
      }
      

Laravel-Specific Quirks

  1. Service Provider Order:

    • Ensure AppServiceProvider runs after runtime setup to avoid $_SERVER pollution.
  2. Artisan Commands:

    • Commands using $_SERVER will fail in CLI mode. Solution: Mock or inject dependencies.
  3. Testing:

    • Use Runner::run() in tests to isolate global state:
      $response = Runner::run(new Kernel(), 'http', [], [
          'HTTP_HOST' => 'test.local',
      ]);
      

Performance Notes

  • FrankenPHP: Enables memory reuse across requests, reducing cold starts.
  • Worker Mode: Avoid heavy bootstrapping in WorkerRuntime (e.g., skip HTTP-specific services).
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky