My Symfony Controllers

Last week when I was presenting my “Events In Practice” talk at GlasgowPHP I had an example slide for a Symfony Controller like below:

namespace Demo;
class UserRegisterController

private $eventDispatcher;
    public function __construct(EventDispatcherInterface $eventDispatcher)
$this->eventDispatcher = $eventDispatcher;
    public function __invoke(Request $request)
$user = new User(...);
new UserRegistered(
        return new JsonResponse();

And I was asked about how I create my controllers with just an __invoke method, the secret? Declaring my Controllers As Services, while Symfony don't "recommend" this approach I find it allows me to keep control of my application structure much better.

The real magic happens in the routing file used

# app/config/routing.yml
path: /hello
defaults: { _controller: app.hello_controller }

By omitting the the :action from the default _controller tag Symfony (from 2.7+ I believe) will automatically call the __invoke method on the controller service.

If you want to read more about this structure of code organisation read up more on the ADR Design Pattern.

GlasgowPHP Slides