The Runtime Component

The Runtime Component

The Runtime Component decouples the bootstrapping logic from any global state to make sure the application can run with runtimes like PHP-FPM, ReactPHP, Swoole, etc. without any changes.

New in version 5.3: The Runtime component was introduced in Symfony 5.3.

Installation

  1. $ composer require symfony/runtime

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Usage

The Runtime component abstracts most bootstrapping logic as so-called runtimes, allowing you to write front-controllers in a generic way. For instance, the Runtime component allows Symfony’s public/index.php to look like this:

  1. <?php
  2. // public/index.php
  3. use App\Kernel;
  4. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  5. return function (array $context) {
  6. return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
  7. };

So how does this front-controller work? At first, the special autoload_runtime.php file is automatically created by the Composer plugin in the component. This file runs the following logic:

  1. It instantiates a Symfony\Component\Runtime\RuntimeInterface;
  2. The callable (returned by public/index.php) is passed to the Runtime, whose job is to resolve the arguments (in this example: array $context);
  3. Then, this callable is called to get the application (App\Kernel);
  4. At last, the Runtime is used to run the application (i.e. calling `$kernel->handle(Request::createFromGlobals())->send()).

Caution

If you use the Composer --no-scripts option, make sure your Composer version is >=2.1.3; otherwise the autoload_runtime.php file won’t be created.

To make a console application, the bootstrap code would look like:

  1. #!/usr/bin/env php
  2. <?php
  3. // bin/console
  4. use App\Kernel;
  5. use Symfony\Bundle\FrameworkBundle\Console\Application;
  6. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  7. return function (array $context) {
  8. $kernel = new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
  9. // returning an "Application" makes the Runtime run a Console
  10. // application instead of the HTTP Kernel
  11. return new Application($kernel);
  12. };

Selecting Runtimes

The default Runtime is Symfony\Component\Runtime\SymfonyRuntime. It works excellent on most applications running with a webserver using PHP-FPM like Nginx or Apache.

The component also provides a Symfony\Component\Runtime\GenericRuntime, which uses PHP’s $_SERVER, $_POST, $_GET, $_FILES and $_SESSION superglobals. You may also use a custom Runtime (e.g. to integrate with Swoole or AWS Lambda).

Use the APP_RUNTIME environment variable or by specifying the extra.runtime.class in composer.json to change the Runtime class:

  1. {
  2. "require": {
  3. "...": "..."
  4. },
  5. "extra": {
  6. "runtime": {
  7. "class": "Symfony\\Component\\Runtime\\GenericRuntime"
  8. }
  9. }
  10. }

Using the Runtime

A Runtime is responsible for passing arguments into the closure and run the application returned by the closure. The Symfony\Component\Runtime\SymfonyRuntime and Symfony\Component\Runtime\GenericRuntime supports a number of arguments and different applications that you can use in your front-controllers.

Resolvable Arguments

The closure returned from the front-controller may have zero or more arguments:

  1. <?php
  2. // public/index.php
  3. use Symfony\Component\Console\Input\InputInterface;
  4. use Symfony\Component\Console\Output\OutputInterface;
  5. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  6. return function (InputInterface $input, OutputInterface $output) {
  7. // ...
  8. };

The following arguments are supported by the SymfonyRuntime:

Symfony\Component\HttpFoundation\Request

A request created from globals.

Symfony\Component\Console\Input\InputInterface

An input to read options and arguments.

Symfony\Component\Console\Output\OutputInterface

Console output to print to the CLI with style.

Symfony\Component\Console\Application

An application for creating CLI applications.

Symfony\Component\Command\Command

For creating one line command CLI applications (using `Command::setCode()).

And these arguments are supported by both the SymfonyRuntime and GenericRuntime (both type and variable name are important):

array $context

This is the same as $_SERVER + $_ENV.

array $argv

The arguments passed to the command (same as $_SERVER['argv']).

array $request

With keys query, body, files and session.

Resolvable Applications

The application returned by the closure below is a Symfony Kernel. However, a number of different applications are supported:

  1. <?php
  2. // public/index.php
  3. use App\Kernel;
  4. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  5. return function () {
  6. return new Kernel('prod', false);
  7. };

The SymfonyRuntime can handle these applications:

Symfony\Component\HttpKernel\HttpKernelInterface

The application will be run with Symfony\Component\Runtime\Runner\Symfony\HttpKernelRunner like a “standard” Symfony application.

Symfony\Component\HttpFoundation\Response

The Response will be printed by Symfony\Component\Runtime\Runner\Symfony\ResponseRunner:

  1. <?php
  2. // public/index.php
  3. use Symfony\Component\HttpFoundation\Response;
  4. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  5. return function () {
  6. return new Response('Hello world');
  7. };

Symfony\Component\Console\Command\Command

To write single command applications. This will use the Symfony\Component\Runtime\Runner\Symfony\ConsoleApplicationRunner:

  1. <?php
  2. use Symfony\Component\Console\Command\Command;
  3. use Symfony\Component\Console\Input\InputInterface;
  4. use Symfony\Component\Console\Output\OutputInterface;
  5. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  6. return function (Command $command) {
  7. $command->setCode(function (InputInterface $input, OutputInterface $output) {
  8. $output->write('Hello World');
  9. });
  10. return $command;
  11. };

Symfony\Component\Console\Application

Useful with console applications with more than one command. This will use the Symfony\Component\Runtime\Runner\Symfony\ConsoleApplicationRunner:

  1. <?php
  2. use Symfony\Component\Console\Application;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  7. return function (array $context) {
  8. $command = new Command('hello');
  9. $command->setCode(function (InputInterface $input, OutputInterface $output) {
  10. $output->write('Hello World');
  11. });
  12. $app = new Application();
  13. $app->add($command);
  14. $app->setDefaultCommand('hello', true);
  15. return $app;
  16. };

The GenericRuntime and SymfonyRuntime also support these generic applications:

Symfony\Component\Runtime\RunnerInterface

The RunnerInterface is a way to use a custom application with the generic Runtime:

  1. <?php
  2. // public/index.php
  3. use Symfony\Component\Runtime\RunnerInterface;
  4. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  5. return function () {
  6. return new class implements RunnerInterface {
  7. public function run(): int
  8. {
  9. echo 'Hello World';
  10. return 0;
  11. }
  12. };
  13. };

callable

Your “application” can also be a callable. The first callable will return the “application” and the second callable is the “application” itself:

  1. <?php
  2. // public/index.php
  3. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  4. return function () {
  5. $app = function() {
  6. echo 'Hello World';
  7. return 0;
  8. };
  9. return $app;
  10. };

void

If the callable doesn’t return anything, the SymfonyRuntime will assume everything is fine:

  1. <?php
  2. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  3. return function () {
  4. echo 'Hello world';
  5. };

Using Options

Some behavior of the Runtimes can be modified through runtime options. They can be set using the APP_RUNTIME_OPTIONS environment variable:

  1. <?php
  2. $_SERVER['APP_RUNTIME_OPTIONS'] = [
  3. 'project_dir' => '/var/task',
  4. ];
  5. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  6. // ...

You can also configure extra.runtime.options in composer.json:

  1. {
  2. "require": {
  3. "...": "..."
  4. },
  5. "extra": {
  6. "runtime": {
  7. "project_dir": "/var/task"
  8. }
  9. }
  10. }

The following options are supported by the SymfonyRuntime:

env (default: APP_ENV environment variable, or "dev")

To define the name of the environment the app runs in.

disable_dotenv (default: false)

To disable looking for .env files.

dotenv_path (default: .env)

To define the path of dot-env files.

use_putenv

To tell Dotenv to set env vars using `putenv() (NOT RECOMMENDED).

prod_envs (default: [“prod”]`)

To define the names of the production envs.

test_envs (default: [“test”]`)

To define the names of the test envs.

Besides these, the GenericRuntime and SymfonyRuntime also support these options:

debug (default: APP_DEBUG environment variable, or true)

Toggles displaying errors.

runtimes

Maps “application types” to a GenericRuntime implementation that knows how to deal with each of them.

error_handler (default: Symfony\Component\Runtime\Internal\BasicErrorHandler or Symfony\Component\Runtime\Internal\SymfonyErrorHandler for SymfonyRuntime)

Defines the class to use to handle PHP errors.

Create Your Own Runtime

This is an advanced topic that describes the internals of the Runtime component.

Using the Runtime component will benefit maintainers because the bootstrap logic could be versioned as a part of a normal package. If the application author decides to use this component, the package maintainer of the Runtime class will have more control and can fix bugs and add features.

Note

Before Symfony 5.3, the Symfony bootstrap logic was part of a Flex recipe. Since recipes are rarely updated by users, bug patches would rarely be installed.

The Runtime component is designed to be totally generic and able to run any application outside of the global state in 6 steps:

  1. The main entry point returns a callable (the “app”) that wraps the application;
  2. The app callable is passed to RuntimeInterface::getResolver(), which returns aSymfony\Component\Runtime\ResolverInterface`. This resolver returns an array with the app callable (or something that decorates this callable) at index 0 and all its resolved arguments at index 1.
  3. The app callable is invoked with its arguments, it will return an object that represents the application.
  4. This application object is passed to RuntimeInterface::getRunner(), which returns aSymfony\Component\Runtime\RunnerInterface`: an instance that knows how to “run” the application object.
  5. The `RunnerInterface::run(object $application) is called and it returns the exit status code as int.
  6. The PHP engine is exited with this status code.

When creating a new runtime, there are two things to consider: First, what arguments will the end user use? Second, what will the user’s application look like?

For instance, imagine you want to create a runtime for ReactPHP:

What arguments will the end user use?

For a generic ReactPHP application, no special arguments are typically required. This means that you can use the Symfony\Component\Runtime\GenericRuntime.

What will the user’s application look like?

There is also no typical React application, so you might want to rely on the PSR-15 interfaces for HTTP request handling.

However, a ReactPHP application will need some special logic to run. That logic is added in a new class implementing Symfony\Component\Runtime\RunnerInterface:

  1. use Psr\Http\Message\ServerRequestInterface;
  2. use Psr\Http\Server\RequestHandlerInterface;
  3. use React\EventLoop\Factory as ReactFactory;
  4. use React\Http\Server as ReactHttpServer;
  5. use React\Socket\Server as ReactSocketServer;
  6. use Symfony\Component\Runtime\RunnerInterface;
  7. class ReactPHPRunner implements RunnerInterface
  8. {
  9. private $application;
  10. private $port;
  11. public function __construct(RequestHandlerInterface $application, int $port)
  12. {
  13. $this->application = $application;
  14. $this->port = $port;
  15. }
  16. public function run(): int
  17. {
  18. $application = $this->application;
  19. $loop = ReactFactory::create();
  20. // configure ReactPHP to correctly handle the PSR-15 application
  21. $server = new ReactHttpServer(
  22. $loop,
  23. function (ServerRequestInterface $request) use ($application) {
  24. return $application->handle($request);
  25. }
  26. );
  27. // start the ReactPHP server
  28. $socket = new ReactSocketServer($this->port, $loop);
  29. $server->listen($socket);
  30. $loop->run();
  31. return 0;
  32. }
  33. }

By extending the GenericRuntime, you make sure that the application is always using this ReactPHPRunner:

  1. use Symfony\Component\Runtime\GenericRuntime;
  2. use Symfony\Component\Runtime\RunnerInterface;
  3. class ReactPHPRuntime extends GenericRuntime
  4. {
  5. private $port;
  6. public function __construct(array $options)
  7. {
  8. $this->port = $options['port'] ?? 8080;
  9. parent::__construct($options);
  10. }
  11. public function getRunner(?object $application): RunnerInterface
  12. {
  13. if ($application instanceof RequestHandlerInterface) {
  14. return new ReactPHPRunner($application, $this->port);
  15. }
  16. // if it's not a PSR-15 application, use the GenericRuntime to
  17. // run the application (see "Resolvable Applications" above)
  18. return parent::getRunner($application);
  19. }
  20. }

The end user will now be able to create front controller like:

  1. <?php
  2. require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
  3. return function (array $context) {
  4. return new SomeCustomPsr15Application();
  5. };

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.