Today is my birthday, but – unusually – I offer the gift: DunglasActionBundle – a replacement for the Symfony controller subsystem.
Since few months, a lot of discussions and experimentations are occurring in the Symfony world to find a better and moderner way to create controllers.
During the past summer, I’ve already switched the API Platform project from the traditional controller system to a variant of the ADR pattern.
Thanks to the support of autowiring I’ve introduced in the version 2.8 of the Dependency Injection Component, it’s now possible to create a generic (and I hope superior) replacement for the controller system of the full stack framework.
With this new system, no more inherited controller class, no more traits, only a plain old callable!
It is as convenient as the original but doesn’t suffer from its drawbacks:
- Action classes are automatically registered as services by the bundle
- Dependencies of action classes are explicitly injected in the constructor (no more ugly access to the service container)
- Dependencies of action classes are automatically injected using the autowiring feature of the Dependency Injection Component
- Only one action per class thanks to the
__invoke()
method (but you’re still free to create classes with more than 1 action if you want to) - 100% compatible with common libraries and bundles including SensioFrameworkExtraBundle annotations
DunglasActionBundle allows to create reusable, framework agnostic (especially when used with the PSR-7 bridge) and easy to unit test actions.
Guess what, it plays very well with the new Symfony micro framework too!
Installation
As usual, use Composer to install this bundle:
composer require dunglas/action-bundle
Then add the bundle in your application kernel:
// app/AppKernel.php public function registerBundles() { return [ // ... new Dunglas\ActionBundle\DunglasActionBundle(), // ... ]; }
Optional: to use the @Route
annotation add the following lines in app/config/routing.yml
:
app_action: resource: '@AppBundle/Action/' type: 'action-annotation'
Usage
- Create an invokable class in the
Action\
namespace of your bundle:
// src/AppBundle/Action/MyAction.php namespace AppBundle\Action; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class MyAction { private $router; private $twig; /** * The action is automatically registered as a service and dependencies are autowired. * Typehint any service you need, it will be automatically injected. */ public function __construct(RouterInterface $router, \Twig_Environment $twig) { $this->router = $router; $this->twig = $twig; } /** * @Route("/myaction", name="my_action") * * Using annotations is not mandatory, XML and YAML configuration files can be used instead. * If you want to decouple your actions from the framework, don't use annotations. */ public function __invoke(Request $request) { if (!$request->isMethod('GET') { // Redirect in GET if the method is not POST return new RedirectResponse($this->router->generateUrl('my_action'), 301); } return new Response($this->twig->render('mytemplate.html.twig')); } }
There is not step 2! You’re already done.
All classes inside of the Action/
directory of your project bundles are automatically registered as services. By convention, those services follow this pattern: action.The\Fully\Qualified\Class\Name
.
For instance, the class in the example is automatically registered with the name action.AppBundle\Action\MyAction
.
Thanks to the autowiring feature of the Dependency Injection Component, you can just typehint dependencies you need in the constructor, they will be automatically injected.
Service definition can easily be customized by explicitly defining a service named according to the same convention:
# app/config/services.yml services: # This is a custom service definition 'action.AppBundle\Action\MyAction': class: 'AppBundle\Action\MyAction' arguments: [ '@router', '@twig' ]
This bundle also hooks into the Routing Component (if it is available): when the @Route
annotation is used as in the example, the route is automatically registered: the bundle guesses the service to map with the path specified in the annotation.
Dive into the TestBundle to discover more examples such as using custom services with ease (no configuration at all) or classes containing several actions.
Using the Symfony Micro Framework
You might be interested to see how this bundle can be used together with the Symfony “Micro” framework.
Here we go:
// MyMicroKernel.php use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Routing\RouteCollectionBuilder; final class MyMicroKernel extends Kernel { use MicroKernelTrait; public function registerBundles() { return [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Dunglas\ActionBundle\DunglasActionBundle(), new AppBundle\AppBundle(), ]; } protected function configureRoutes(RouteCollectionBuilder $routes) { // Specify explicitly the controller $routes->add('/', 'action.AppBundle\Action\MyAction', 'my_route'); // Alternatively, use @Route annotations // $routes->import('@AppBundle/Action/', '/', 'action-annotation'); } protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader) { $c->loadFromExtension('framework', ['secret' => 'MySecretKey']); } }
Amazing isn’t it?
Want to see a more advanced example? Checkout our test micro kernel.
You like this bundle? Give it a star on GitHub!