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 providing a flexible runtime entry point and bootstrapping layer. It standardizes how apps are started across environments and integrations, improving portability and testability.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/runtime
    

    For Laravel, ensure compatibility with your PHP version (v8.x requires PHP 8.4+; v7.x works with PHP 7.2+).

  2. Basic Usage: Create a Runtime instance in your entry point (e.g., public/index.php or artisan):

    use Symfony\Component\Runtime\Runner\RunnerInterface;
    use Symfony\Component\Runtime\SymfonyRuntime;
    
    $runner = new SymfonyRuntime(); // Default runner
    $runtime = new SymfonyRuntime($runner);
    $runtime->boot();
    
  3. First Use Case: Replace Laravel’s default index.php with a runtime-aware entry point:

    // public/index.php
    require __DIR__.'/../vendor/autoload.php';
    
    $runtime = new SymfonyRuntime();
    $runtime->boot();
    
    // Delegate to Laravel's kernel (now runtime-aware)
    $kernel = new App\Kernel();
    $request = Request::createFromGlobals();
    $response = $kernel->handle($request);
    $response->send();
    
  4. Key Files to Review:


Implementation Patterns

Core Workflows

1. Runtime-Aware Kernel Integration

Extend Laravel’s Kernel to work with Symfony Runtime:

// app/Kernel.php
use Symfony\Component\Runtime\RuntimeInterface;

class Kernel extends HttpKernel
{
    public function __construct(RuntimeInterface $runtime = null)
    {
        $this->runtime = $runtime;
        parent::__construct($this->getContainer(), $this->requestStack, $this->httpKernel);
    }

    protected function getContainer()
    {
        if ($this->runtime) {
            $this->runtime->boot();
        }
        return parent::getContainer();
    }
}

2. Custom Runner for Laravel

Implement a RunnerInterface to handle Laravel-specific logic (e.g., Artisan commands, HTTP requests):

// app/Runtime/LaravelRunner.php
use Symfony\Component\Runtime\Runner\RunnerInterface;

class LaravelRunner implements RunnerInterface
{
    public function run(array $arguments = []): int
    {
        return (new Artisan())->run($arguments);
    }
}

3. Environment Isolation

Load .env files per runtime (e.g., separate .env.testing for tests):

$runtime = new SymfonyRuntime(new SymfonyRuntimeOptions([
    'env' => 'testing',
    'extraEnvFiles' => ['.env.testing'],
]));

4. Dependency Injection

Bind the runtime to Laravel’s container:

// config/app.php
'bindings' => [
    Symfony\Component\Runtime\RuntimeInterface::class => function ($app) {
        return new SymfonyRuntime();
    },
];

5. Multi-Runtime Deployment

Use different runners for HTTP/CLI/workers:

// public/index.php (HTTP)
$runtime = new SymfonyRuntime(new HttpRunner());

// artisan (CLI)
$runtime = new SymfonyRuntime(new ArtisanRunner());

// worker.php (RoadRunner)
$runtime = new SymfonyRuntime(new WorkerRunner());

Integration Tips

Laravel-Specific Patterns

  1. Replace Global State:

    • Replace $_SERVER['HTTP_HOST'] with dependency-injected Request or Runtime:
      $host = $runtime->getOptions()->get('http_host'); // From runtime options
      
    • Use RuntimeInterface::getProjectDir() instead of __DIR__ or base_path().
  2. Artisan Commands: Wrap commands in a runtime-aware closure:

    $runtime->run(function () {
        Artisan::call('migrate');
    });
    
  3. Middleware: Inject RuntimeInterface into middleware:

    public function handle($request, Closure $next, RuntimeInterface $runtime)
    {
        $runtime->boot();
        return $next($request);
    }
    
  4. Service Providers: Boot the runtime in a provider:

    public function boot()
    {
        $this->app->make(RuntimeInterface::class)->boot();
    }
    
  5. Testing: Mock the runtime for isolated tests:

    $runtime = $this->createMock(RuntimeInterface::class);
    $runtime->method('getOptions')->willReturn(new SymfonyRuntimeOptions(['env' => 'testing']));
    $this->app->instance(RuntimeInterface::class, $runtime);
    

Performance Optimizations

  • FrankenPHP/RoadRunner: Enable automatic detection:
    $runtime = new SymfonyRuntime(new FrankenPhpRunner());
    
  • Lazy Bootstrapping: Defer runtime boot until first use:
    $runtime = new SymfonyRuntime();
    $runtime->bootIfNotBooted(); // Only boots if not already booted
    

Security

  • Environment Variables: Use runtime-scoped .env files to prevent leaks:
    $runtime = new SymfonyRuntime(new SymfonyRuntimeOptions([
        'extraEnvFiles' => ['.env.production', '.env.tenant-' . $tenantId],
    ]));
    
  • Secret Management: Integrate with symfony/options-resolver to validate env vars:
    $options = new SymfonyRuntimeOptions([
        'requiredEnvVars' => ['APP_KEY', 'DB_PASSWORD'],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Global State Residue:

    • Issue: Forgetting to replace $_SERVER/$_ENV in legacy code.
    • Fix: Use symfony/var-dumper to audit globals:
      var_dump($_SERVER, $_ENV); // Check for unintended usage
      
    • Tool: Run php -d display_errors=1 to catch deprecated global access.
  2. Circular Dependencies:

    • Issue: Runtime bootstrapping too early in service providers.
    • Fix: Use lazy loading:
      $this->app->booting(function () {
          $this->app->make(RuntimeInterface::class)->bootIfNotBooted();
      });
      
  3. Environment Mismatches:

    • Issue: .env files not loaded in expected order.
    • Fix: Explicitly define extraEnvFiles:
      $runtime = new SymfonyRuntime(new SymfonyRuntimeOptions([
          'env' => 'production',
          'extraEnvFiles' => ['.env', '.env.production.local'],
      ]));
      
  4. Runner Conflicts:

    • Issue: Multiple runners (e.g., HTTP + CLI) interfering.
    • Fix: Use RunnerInterface::supports() to validate:
      if (!$runner->supports($this->getSapiName())) {
          throw new \RuntimeException('Unsupported SAPI');
      }
      
  5. PHP Version Mismatches:

    • Issue: Laravel 10 (PHP 8.2+) with Symfony Runtime v8 (PHP 8.4+).
    • Fix: Pin to compatible versions:
      composer require symfony/runtime:^7.4
      
  6. Request Object Reuse:

    • Issue: Duplicate Request objects in kernel methods.
    • Fix: Use Symfony Runtime’s built-in reuse:
      $kernel = new Kernel($runtime);
      $response = $kernel->handle($request); // Request reused if already created
      

Debugging Tips

  1. Runtime Introspection:

    • Check booted state:
      $runtime->isBooted(); // bool
      
    • Inspect options:
      $runtime->getOptions()->all(); // array
      
  2. Logging:

    • Enable debug logging:
      $runtime = new SymfonyRuntime(new SymfonyRuntimeOptions([
          'debug' => true,
      ]));
      
  3. Common Errors:

    • "Runtime already booted": Call bootIfNotBooted() instead of boot().
    • "Unsupported SAPI": Ensure the runner supports your environment (e.g., cli, fpm).
    • "Missing env vars": Validate requiredEnvVars in SymfonyRuntimeOptions.
  4. Profiling:

    • Measure boot time:
      $start = microtime(true);
      $runtime->boot();
      echo microtime(true) - $start; // Boot duration
      

Extension Points

  1. Custom Runners:
    • Implement RunnerInterface for new environments (e.g
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport