Symfony can be used as a microframework since Symfony 2.8. In fact, you can
create fully working Symfony applications in a single file thanks to the
MicroKernelTrait
.
In Symfony 5.1 we've improved MicroKernelTrait
to allow using the Kernel
as a registry of autowired controllers and service factories. This example shows
a single-file Symfony application that defines a service which is autowired in
the controller defined in the same file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
// index.php
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
require __DIR__.'/vendor/autoload.php';
class MySymfonyApp extends Kernel
{
use MicroKernelTrait;
protected function configureContainer(ContainerConfigurator $container): void
{
$container->services()
->load('App\\', '../src')
->set(Foo::class)->factory([$this, 'createFoo']);
}
public function createFoo(Bar $bar)
{
return new Foo($bar);
}
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->add('home', '/')->controller([$this, 'helloAction']);
}
public function helloAction(Foo $foo)
{
return new Response('Hello '.get_class($foo));
}
}
$app = new MySymfonyApp('dev', true);
$request = Request::createFromGlobals();
$response = $app->handle($request);
$response->send();
$app->terminate($request, $response);
thank you! very useful for testing
This seems to be quite an elegant construction for tiny apps. However, I find the last paragraph unnecesairly verbose. Is there a reason not to provide a (static) main method to execute the microkernel?
Thank you!!!
@Josef check https://github.com/symfony/symfony/pull/36652 it might provide a way to reduce the boilerplate in the bootstrap file.