PHP development blog ·

Action-Domain-Responder in practice: how we rewrote an e-shop API

Why we chose the Action-Domain-Responder architecture over MVC for a new e-shop API, what actions, domains and responders look like in PHP, and what the hasHasInvoice element taught us.

When a large e-shop we work for was preparing a new mobile app, it had three separate REST APIs: one for the mobile app, one for the website frontend and one for the SAP integration. We decided to rewrite the API so that a single new one would serve both mobile and web. That simplified maintenance, since we now look after one API instead of several similar ones. On the other hand, every request had to be approved by all the teams involved. For the new API we chose the Action-Domain-Responder (ADR) architecture, and here's what we learned.

Why not classic MVC

MVC was created for desktop user interfaces long before the web existed, let alone APIs. So it doesn't fit HTTP APIs very well: a controller usually handles dozens of actions, a view often has nothing to do for a JSON response, and the arrows between model, view and controller point in different directions depending on which diagram you happen to read.

In 2014, Paul M. Jones described ADR as a refinement of MVC for the request/response world. It's more than renaming the layers:

  • It matches how an API behaves: a request flows in one direction, from input to response.
  • It separates code better: each endpoint has its own class and the logic doesn't depend on HTTP.
  • The domain can be called without HTTP: you can run the same logic from the console or a queue.
  • The responder is one-way: it only turns the result into a response and never calls back into the action.

Three parts and their MVC counterparts

ADRMVC counterpartWhat it does
ActionControllerconfigures one endpoint: input, access, domain and response type
DomainModeltakes the input, runs the logic and returns an output or an error
ResponderViewbuilds the HTTP response from the output (status, JSON, file, error)

Infrastructure in the background drives it all: routing, middleware, validation and choosing the responder. We wrote it from scratch. The application boots through Nette but no longer depends on the framework directly, and we later reused the same infrastructure for another API that connected the product catalogue to the website.

Action: one class per endpoint

The main difference from a typical API is that an action handles a single operation, i.e. one combination of URL and GET, POST, PUT or DELETE method. We tell the classes apart by a Read, Create, Update or Delete prefix. The action computes nothing itself; it only says how the request should be handled:

  • middleware, e.g. authenticating the user,
  • an input factory that builds the input object from the request,
  • a path into the OpenAPI schema that the infrastructure validates the request against before it reaches the domain,
  • the domain that handles the request,
  • the responder type, if it shouldn't be the default JSON.
final class ReadOrderAction implements ActionInterface
{
    public function getMiddleware(): array
    {
        return [CustomerAuthMiddleware::class];
    }

    public function getInputFactoryClass(): string
    {
        return ReadOrderInputFactory::class;
    }

    public function getDomainClass(): string
    {
        return ReadOrderDomain::class;
    }

    public function getSchemaPath(): string
    {
        return '#/paths/~1orders~1{id}/get';
    }
}

The directory structure follows the same idea: Action/Order/ holds every operation on an order and its input factories, and Domain/Order/ holds the domain classes, the input and output objects (Input, Output) and the exceptions for the endpoint's error states.

Domain: input in, output out

The domain gets its dependencies through dependency injection and has a single public method, __invoke(). It takes an input object and returns an output object. It knows nothing about HTTP.

final class ReadOrderDomain
{
    public function __construct(
        private OrderRepository $orders,
    ) {
    }

    public function __invoke(ReadOrderInput $input): OrderOutput
    {
        $order = $this->orders->find($input->orderId)
            ?? throw new OrderNotFoundException($input->orderId);

        return OrderOutput::fromOrder($order);
    }
}

Errors are handled with exceptions. An unexpected exception ends up as a generic 500 error. Exceptions that implement our error interface turn into a response with a specific HTTP status, error code and a clear message the client application understands.

Responder: a response for each type of output

Responders are part of the infrastructure. We have four: Empty (no body), Json (the default), File (a download) and Error. The output object is a plain DTO with getters, and the JSON responder generates the response keys from them using a name normaliser.

Here's a story about that. According to the spec, the response had to contain a hasInvoice element. The getter getHasInvoice() sounded odd, so it was renamed to hasInvoice(). Only later did someone notice that the normaliser strips the "has" prefix just like "get", so the response contained only invoice. The fix? A method called hasHasInvoice(). Since then we don't use words like "has" and "is" in response element names at all. The lesson: if you generate JSON from method names, define the normalisation rules up front, or write the mapping explicitly.

Did it work out?

Yes. Each endpoint is small and self-contained, so you can read, test and change it without worrying about breaking neighbouring actions. A new developer finds everything about an endpoint in one place, and validation against OpenAPI keeps the documentation in line with reality.

The best proof came about a year later. Other teams found out how the new API worked and started building new endpoints themselves, so there was no work left on this API for our team. It's hard to imagine a better outcome for an architecture.

When to use ADR

  • It pays off for an API with dozens of endpoints, worked on by several teams or serving several clients (mobile, web, internal systems).
  • It pays off less for a small application with a handful of endpoints, where custom infrastructure adds more work than it saves.

Planning a new API, or stuck with an old one nobody wants to maintain? We can take it over or design a new one. Get in touch using the form below.

Further reading: Paul M. Jones, Action Domain Responder (the original description of the pattern), pmjones/adr on GitHub, Implementing Action-Domain-Responder Pattern With Symfony.

Related

Contact us


Send us an enquiry when we are not available on the phone