{
    "href": "/post/2016/03/08/command-bus-and-action-domain-responder/",
    "relId": "2016/03/08/command-bus-and-action-domain-responder",
    "title": "Command Bus and Action-Domain-Responder",
    "author": "pmjones",
    "markup": "html",
    "tags": [
        {
            "href": "/tag/adr/",
            "relId": "adr",
            "title": "Action Domain Responder",
            "author": null,
            "created": "2020-08-17 21:07:42 UTC",
            "updated": [
                "2020-08-17 21:07:42 UTC",
                "2020-09-22 15:41:16 UTC",
                "2020-10-14 18:20:29 UTC",
                "2020-10-14 18:36:31 UTC",
                "2020-10-14 18:36:53 UTC",
                "2020-10-14 18:37:08 UTC",
                "2020-10-14 18:37:48 UTC",
                "2020-10-14 18:39:26 UTC",
                "2020-10-14 19:03:17 UTC",
                "2020-10-14 19:03:35 UTC",
                "2020-10-26 18:12:53 UTC"
            ],
            "markup": "markdown"
        },
        {
            "href": "/tag/php/",
            "relId": "php",
            "title": "PHP",
            "author": null,
            "created": null,
            "updated": [],
            "markup": "markdown"
        },
        {
            "href": "/tag/programming/",
            "relId": "programming",
            "title": "Programming",
            "author": null,
            "created": null,
            "updated": [],
            "markup": "markdown"
        }
    ],
    "created": "2016-03-08 17:08:59 UTC",
    "updated": [
        "2016-03-08 17:08:59 UTC"
    ],
    "html": "<p>Over the past few weeks, different people have asked me where a Command Bus goes in an <a href=\"http://pmjones.io/adr/\">Action-Domain-Responder</a> system. While I\u2019m not a DDD expert, after brushing up on the subject a little, my answer is: \u201cIn the Domain.\u201d</p>\n<p>First, let\u2019s recall the three components in ADR:</p>\n<ul>\n<li>\n<p>\u201cAction\u201d is the logic that connects the Domain and Responder. It uses the request input to interact with the Domain, and passes the Domain output to the Responder. (The Action is intentionally \u201cdumb\u201d: it should have no logic at all, aside from perhaps the most minimal of ternaries to allow for default input values. If the Action has a conditional, it is doing too much.)</p>\n</li>\n<li>\n<p>\u201cDomain\u201d is the logic to manipulate the domain, session, application, and environment data, modifying state and persistence as needed. (The word \u201cDomain\u201d here is explicitly intended to remind you of \u201cdomain logic\u201d and \u201cdomain-driven design.\u201d)</p>\n</li>\n<li>\n<p>\u201cResponder\u201d is the logic to build an HTTP response or response description. It deals with body content, templates and views, headers and cookies, status codes, and so on.</p>\n</li>\n</ul>\n<p>Next, let\u2019s see what Command Bus is. There\u2019s a lot written about it elsewhere \u2026</p>\n<ul>\n<li>\n<p><a href=\"http://php-and-symfony.matthiasnoback.nl/2015/01/a-wave-of-command-buses/\">A wave of command buses</a></p>\n</li>\n<li>\n<p><a href=\"http://php-and-symfony.matthiasnoback.nl/2015/01/responsibilities-of-the-command-bus/\">Responsibilities of the command bus</a></p>\n</li>\n<li>\n<p><a href=\"http://www.sitepoint.com/command-buses-demystified-a-look-at-the-tactician-package/\">Command Buses Demystified</a></p>\n</li>\n<li>\n<p><a href=\"http://shawnmc.cool/command-bus\">Command Bus: An overview of implementation, advantages, and challenges</a></p>\n</li>\n<li>\n<p><a href=\"https://www.reddit.com/r/PHP/comments/29a6qz/what_am_i_missing_with_this_whole_command_bus/\">What am I missing with this whole command bus craze?</a></p>\n</li>\n</ul>\n<p>\u2026 so I\u2019ll try to sum up here:</p>\n<ul>\n<li>\n<p>A \u201cCommand\u201d is a typed or named set of inputs (essentially a data-transfer object) that gets sent to a \u201cCommand Bus.\u201d</p>\n</li>\n<li>\n<p>The \u201cCommand Bus\u201d then hands off the \u201cCommand\u201d to a \u201cCommand Handler\u201d specific to that \u201cCommand\u201d; the \u201cCommand Bus\u201d figures out which \u201cCommand Handler\u201d to use from the name or type of the \u201cCommand.\u201d</p>\n</li>\n<li>\n<p>The \u201cCommand Handler\u201d uses the \u201cCommand\u201d inputs to perform some sort of activity.</p>\n</li>\n</ul>\n<p>This series of objects is part of an overarching architectural pattern called Command Query Responsibility Segregation (see <a href=\"http://culttt.com/2015/01/14/command-query-responsibility-segregation-cqrs/\">here</a> and <a href=\"http://www.codeproject.com/Articles/555855/Introduction-to-CQRS\">here</a>). Under CQRS, writes (Commands) are handled separately from reads (Queries). Handling a Command modifies data but does not return a result, while handling a Query returns a result but must not modify data.</p>\n<p>This means that a Command Bus does not actually return a result for inspection. You dump a Command into the Bus, and you\u2019re done; there\u2019s no checking for errors at that time. To conform to CQRS properly, you have to perform a separate Query in order to determine the result of the Command.</p>\n<p>At this point, just from having read the literature on the patterns and concepts, we can see that Command Bus and its related components are part of the domain layer, not part of the user interface layer. With that in mind, it seems like Command Bus is a candidate for the \u201cDomain\u201d portion of Action-Domain-Responder, to be used like this in an Action:</p>\n<pre><code class=\"php\">class CreateItemAction\n{\n    public function __construct(\n        CommandBus $domain,\n        CommandResponder $responder\n    ) {\n        $this-&gt;domain = $domain;\n        $this-&gt;responder = $responder;\n    }\n\n    public function __invoke(Request $request)\n    {\n        $input = $request-&gt;getParsedBody();\n        $command = new CreateItemCommand(\n            $input['item_name'],\n            $input['item_description']\n        );\n        $this-&gt;domain-&gt;handle($command);\n        return $this-&gt;responder-&gt;createResponse();\n    }\n}\n</code></pre>\n<p>So the Action gets constructed with a CommandBus element as an entry point into the Domain, and with a generic Responder to build the response. At invocation time, the user interface code sends along the current HTTP request; the Action pulls data out of it to create Command to send to the Command Bus, then tells the Responder to create an HTTP response. (Because a Command never returns anything, one Responder should suffice for all Commands in this setup.)</p>\n<p>This is straightforward as an minimal case, but I think it avoids at least two substantial issues.</p>\n<ol>\n<li>\n<p>Where does input validation go? (Input validation, or form validation, is separate from domain model validation.)</p>\n</li>\n<li>\n<p>Where does error handling go? (While a Command might not <em>return</em> anything, the various elements related to CQRS might very well throw exceptions or raise errors.)</p>\n</li>\n</ol>\n<p>In what we think of as server-side MVC, those two concerns might well be placed in the Controller somewhere. Translating a Controller method directly to an Action, that might look something like this:</p>\n<pre><code class=\"php\">    public function __invoke(Request $request)\n    {\n        // get the input and validate it\n        $input = $request-&gt;getParsedBody();\n        if (! $this-&gt;validate($input)) {\n            // create an \"invalid input\" response\n            return $this-&gt;responder-&gt;invalid($input);\n        }\n\n        // create the command\n        $command = new CreateItemCommand(\n            $input['item_name'],\n            $input['item_description']\n        );\n\n        // try the command\n        try {\n            $this-&gt;domain-&gt;handle($command);\n            // succcess!\n            return $this-&gt;responder-&gt;success();\n        } catch (Exception $e) {\n            // there was some sort of subsequent failure\n            return $this-&gt;responder-&gt;failure($e);\n        }\n    }\n</code></pre>\n<p>On consideration, that seems like a lot of extraneous activity in the user interface layer. In ADR, the Action is intentionally supposed to be dumb. It should not be doing anything even remotely interesting, and certainly should not be dealing with any conditional logic.</p>\n<p>As such, I say that Command-related activity should be taken out of the Action entirely, and relegated to something like an Application Service or some other Domain entry point. That Service is what should perform the Command-related activity.</p>\n<p>Further, while a Command may not return a result, a Service certainly can. This means that the Action can call the Domain and get back a <a href=\"http://paul-m-jones.com/archives/6043\">Domain Payload</a> as a result, which can then be passed to the Responder for presentation.</p>\n<p>Under that way of thinking, we get something more like this:</p>\n<pre><code class=\"php\">class CreateItemAction\n{\n    public function __construct(\n        ItemService $domain,\n        CreateItemResponder $responder\n    ) {\n        $this-&gt;domain = $domain;\n        $this-&gt;responder = $responder;\n    }\n\n    public function __invoke(Request $request)\n    {\n        $input = $request-&gt;getParsedBody();\n        $payload = $this-&gt;domain-&gt;create($input);\n        return $this-&gt;responder-&gt;createResponse($payload);\n    }\n}\n\nclass ItemService\n{\n    public function create(array $input)\n    {\n        if (! $this-&gt;validate($input)) {\n            // create an \"invalid input\" response\n            return new InvalidInputPayload($input);\n        }\n\n        // create the command\n        $command = new CreateItemCommand(\n            $input['item_name'],\n            $input['item_description']\n        );\n\n        // try the command\n        try {\n            $this-&gt;domain-&gt;handle($command);\n            return new CommandAcceptedPayload();\n        } catch (Exception $e) {\n            return new CommandRejectedPayload($e);\n        }\n    }\n}\n</code></pre>\n<p>Now the Domain is fully separated from the user interface. It can be used with both HTTP and command-line interfaces, and tested separately from them. Per the ADR pattern, the Responder becomes responsible for examining the Payload to see what kind of presentation to deliver to the client. Different Payloads result in different responses being built. Finally, the Action becomes entirely uninteresting; all of the business logic has been pushed down into the Domain, where it belongs.</p>\n<p>So, to sum up: Command Bus is a domain layer pattern, and should be used in the Domain, not in the Action. A Command cannot return a result, but a Service can, so the entry point into the Domain is probably better as a Service that returns a Payload. This keeps the HTTP and CLI user interface logic well separated from business logic, and independently testable and reusable.</p>\n<hr>\n<p class=\"reddit-links\">Read the Reddit discussion about this post <a href=\"https://www.reddit.com/r/PHP/comments/49jh4r/command_bus_and_actiondomainresponder/\">here</a>.</p>\n"
}
