Contributed by
Yonel Ceruto
in
#57408
Symfony allows you to create single-file applications which are useful for
simple workers, microservices, CLI tools, minimal APIs, and more. Here's an
example of a single-file application as it looks today:
// index.php
use App\Generator\NumberGenerator;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Attribute\Route;
require __DIR__.'/vendor/autoload.php';
class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function registerBundles(): array
{
return [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
];
}
protected function configureContainer(ContainerConfigurator $container): void
{
$container->extension('framework', [
'secret' => 'S0ME_SECRET'
]);
// alternatively, define this in a configuration file and load it as:
// $container->import(__DIR__.'/../config/framework.yaml');
}
#[Route('/random/{limit}', name: 'random_number')]
public function randomNumber(int $limit, NumberGenerator $numberGenerator): JsonResponse
{
return new JsonResponse([
'number' => $numberGenerator->generate($limit),
]);
}
}
return static function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
}
In Symfony 7.2, we've simplified the MicroKernelTrait
. Now, the same
application looks like this:
// index.php
use App\Generator\NumberGenerator;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Attribute\Route;
require __DIR__.'/vendor/autoload.php';
class Kernel extends BaseKernel
{
use MicroKernelTrait;
#[Route('/random/{limit}', name: 'random_number')]
public function __invoke(int $limit, NumberGenerator $numberGenerator): JsonResponse
{
return new JsonResponse([
'number' => $numberGenerator->generate($limit),
]);
}
}
return static function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
}
The changes introduced in Symfony 7.2 are:
- The
config/
directory is now optional, so you can omit it entirely if you
define the configuration in theconfigureContainer()
method; - The
bundles.php
file is also optional and theregisterBundles()
method
now defaults toyield new FrameworkBundle();
. This removes the need to
define that method when no other bundles are loaded; - Support for service injection in invokable actions using the
__invoke()
method; - The
framework.secret
parameter is now optional (related to a different
pull request that will be covered in another blog post).
Sponsor the Symfony project.