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:

<?php

namespace Demo;

class UserRegisterController
{
    private $eventDispatcher;

    public function __construct(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    public function __invoke(Request $request)
    {
        $user = new User(...);

        $this->eventDispatcher->dispatch(
            'event.user_registered',
            new UserRegistered(
                $user
            )
        );

        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
hello:
    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

Categories: Symfony, php, code