Building your own Framework with the MicroKernelTrait

Building your own Framework with the MicroKernelTrait

The default Kernel class included in Symfony applications uses a Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait to configure the bundles, the routes and the service container in the same class.

This micro-kernel approach is flexible, allowing you to control your application structure and features.

A Single-File Symfony Application

Start with a completely empty directory and install these Symfony components via Composer:

  1. $ composer require symfony/config symfony/http-kernel \
  2. symfony/http-foundation symfony/routing \
  3. symfony/dependency-injection symfony/framework-bundle

Next, create an index.php file that defines the kernel class and runs it:

  1. // index.php
  2. use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
  3. use Symfony\Component\Config\Loader\LoaderInterface;
  4. use Symfony\Component\DependencyInjection\ContainerBuilder;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Kernel as BaseKernel;
  8. use Symfony\Component\Routing\RouteCollectionBuilder;
  9. require __DIR__.'/vendor/autoload.php';
  10. class Kernel extends BaseKernel
  11. {
  12. use MicroKernelTrait;
  13. public function registerBundles()
  14. {
  15. return [
  16. new Symfony\Bundle\FrameworkBundle\FrameworkBundle()
  17. ];
  18. }
  19. protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
  20. {
  21. // PHP equivalent of config/packages/framework.yaml
  22. $c->loadFromExtension('framework', [
  23. 'secret' => 'S0ME_SECRET'
  24. ]);
  25. }
  26. protected function configureRoutes(RouteCollectionBuilder $routes)
  27. {
  28. // kernel is a service that points to this class
  29. // optional 3rd argument is the route name
  30. $routes->add('/random/{limit}', 'kernel::randomNumber');
  31. }
  32. public function randomNumber($limit)
  33. {
  34. return new JsonResponse([
  35. 'number' => random_int(0, $limit),
  36. ]);
  37. }
  38. }
  39. $kernel = new Kernel('dev', true);
  40. $request = Request::createFromGlobals();
  41. $response = $kernel->handle($request);
  42. $response->send();
  43. $kernel->terminate($request, $response);

That’s it! To test it, start the Symfony Local Web Server:

  1. $ symfony server:start

Then see the JSON response in your browser: http://localhost:8000/random/10

The Methods of a “Micro” Kernel

When you use the MicroKernelTrait, your kernel needs to have exactly three methods that define your bundles, your services and your routes:

registerBundles()

This is the same registerBundles() that you see in a normal kernel.

configureContainer(ContainerBuilder $c, LoaderInterface $loader)

This method builds and configures the container. In practice, you will use loadFromExtension to configure different bundles (this is the equivalent of what you see in a normal config/packages/* file). You can also register services directly in PHP or load external configuration files (shown below).

configureRoutes(RouteCollectionBuilder $routes)

Your job in this method is to add routes to the application. The RouteCollectionBuilder has methods that make adding routes in PHP more fun. You can also load external routing files (shown below).

Advanced Example: Twig, Annotations and the Web Debug Toolbar

The purpose of the MicroKernelTrait is not to have a single-file application. Instead, its goal to give you the power to choose your bundles and structure.

First, you’ll probably want to put your PHP classes in an src/ directory. Configure your composer.json file to load from there:

  1. {
  2. "require": {
  3. "...": "..."
  4. },
  5. "autoload": {
  6. "psr-4": {
  7. "App\\": "src/"
  8. }
  9. }
  10. }

Then, run composer dump-autoload to dump your new autoload config.

Now, suppose you want to use Twig and load routes via annotations. Instead of putting everything in index.php, create a new src/Kernel.php to hold the kernel. Now it looks like this:

  1. // src/Kernel.php
  2. namespace App;
  3. use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
  4. use Symfony\Component\Config\Loader\LoaderInterface;
  5. use Symfony\Component\DependencyInjection\ContainerBuilder;
  6. use Symfony\Component\HttpKernel\Kernel as BaseKernel;
  7. use Symfony\Component\Routing\RouteCollectionBuilder;
  8. class Kernel extends BaseKernel
  9. {
  10. use MicroKernelTrait;
  11. public function registerBundles()
  12. {
  13. $bundles = [
  14. new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
  15. new \Symfony\Bundle\TwigBundle\TwigBundle(),
  16. ];
  17. if ($this->getEnvironment() == 'dev') {
  18. $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
  19. }
  20. return $bundles;
  21. }
  22. protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
  23. {
  24. $loader->load(__DIR__.'/../config/framework.yaml');
  25. // configure WebProfilerBundle only if the bundle is enabled
  26. if (isset($this->bundles['WebProfilerBundle'])) {
  27. $c->loadFromExtension('web_profiler', [
  28. 'toolbar' => true,
  29. 'intercept_redirects' => false,
  30. ]);
  31. }
  32. }
  33. protected function configureRoutes(RouteCollectionBuilder $routes)
  34. {
  35. // import the WebProfilerRoutes, only if the bundle is enabled
  36. if (isset($this->bundles['WebProfilerBundle'])) {
  37. $routes->import('@WebProfilerBundle/Resources/config/routing/wdt.xml', '/_wdt');
  38. $routes->import('@WebProfilerBundle/Resources/config/routing/profiler.xml', '/_profiler');
  39. }
  40. // load the annotation routes
  41. $routes->import(__DIR__.'/../src/Controller/', '/', 'annotation');
  42. }
  43. // optional, to use the standard Symfony cache directory
  44. public function getCacheDir()
  45. {
  46. return __DIR__.'/../var/cache/'.$this->getEnvironment();
  47. }
  48. // optional, to use the standard Symfony logs directory
  49. public function getLogDir()
  50. {
  51. return __DIR__.'/../var/log';
  52. }
  53. }

Before continuing, run this command to add support for the new dependencies:

  1. $ composer require symfony/yaml symfony/twig-bundle symfony/web-profiler-bundle doctrine/annotations

Unlike the previous kernel, this loads an external config/framework.yaml file, because the configuration started to get bigger:

  • YAML

    1. # config/framework.yaml
    2. framework:
    3. secret: S0ME_SECRET
    4. profiler: { only_exceptions: false }
  • XML

    1. <!-- config/framework.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd
    7. http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    8. <framework:config secret="S0ME_SECRET">
    9. <framework:profiler only-exceptions="false"/>
    10. </framework:config>
    11. </container>
  • PHP

    1. // config/framework.php
    2. $container->loadFromExtension('framework', [
    3. 'secret' => 'S0ME_SECRET',
    4. 'profiler' => [
    5. 'only_exceptions' => false,
    6. ],
    7. ]);

This also loads annotation routes from an src/Controller/ directory, which has one file in it:

  1. // src/Controller/MicroController.php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Routing\Annotation\Route;
  5. class MicroController extends AbstractController
  6. {
  7. /**
  8. * @Route("/random/{limit}")
  9. */
  10. public function randomNumber($limit)
  11. {
  12. $number = random_int(0, $limit);
  13. return $this->render('micro/random.html.twig', [
  14. 'number' => $number,
  15. ]);
  16. }
  17. }

Template files should live in the templates/ directory at the root of your project. This template lives at templates/micro/random.html.twig:

  1. <!-- templates/micro/random.html.twig -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>Random action</title>
  6. </head>
  7. <body>
  8. <p>{{ number }}</p>
  9. </body>
  10. </html>

Finally, you need a front controller to boot and run the application. Create a public/index.php:

  1. // public/index.php
  2. use App\Kernel;
  3. use Doctrine\Common\Annotations\AnnotationRegistry;
  4. use Symfony\Component\HttpFoundation\Request;
  5. $loader = require __DIR__.'/../vendor/autoload.php';
  6. // auto-load annotations
  7. AnnotationRegistry::registerLoader([$loader, 'loadClass']);
  8. $kernel = new Kernel('dev', true);
  9. $request = Request::createFromGlobals();
  10. $response = $kernel->handle($request);
  11. $response->send();
  12. $kernel->terminate($request, $response);

That’s it! This /random/10 URL will work, Twig will render, and you’ll even get the web debug toolbar to show up at the bottom. The final structure looks like this:

  1. your-project/
  2. ├─ config/
  3. └─ framework.yaml
  4. ├─ public/
  5. | └─ index.php
  6. ├─ src/
  7. | ├─ Controller
  8. | | └─ MicroController.php
  9. | └─ Kernel.php
  10. ├─ templates/
  11. | └─ micro/
  12. | └─ random.html.twig
  13. ├─ var/
  14. | ├─ cache/
  15. └─ log/
  16. ├─ vendor/
  17. └─ ...
  18. ├─ composer.json
  19. └─ composer.lock

As before you can use the Symfony Local Web Server:

  1. cd public/
  2. $ symfony server:start

Then visit the page in your browser: http://localhost:8000/random/10

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