How should the outputting/conversion of JSON be separated?

Hi,

In Odan’s ebook (which I did buy) it says:

In this example, we create a “barrier” between source data and output, so that schema changes do not affect the clients. For the sake of simplicity, this is done using the same method. In reality, you would separate the input data mapping and output JSON conversion into separate parts of your application.

This is in reference to the UserCreateAction class.

I’m intending incorporating a front end framework, Angular perhaps, in my app. So how should the outputting/conversion of JSON be separated? Do you have an example you can show me?

Thank you,

FBS

Hi!

According to ADR the Action should not be responsible for transforming the Domain result into proper structure for the (JSON) response. The Responder is entirely in charge of setting headers, setting the body content, picking content types, rendering templates, and so on. Note that a Responder may incorporate a Template View , Transform View , or any other kind of body content building system. In trivial cases, it may be reasonable to collect different sets of Responder logic, e.g., corresponding to the presentation logic for different Actions, into a single class as well.
In more complex scenarios a particular Responder would be a better choice as I mentioned in the tutorial.

In case you want to separate the output conversion (transformation), you could create a specific Responder class, e.g. UserCreateResponder. Then the Action should invoke this responder and return the result from it as Response object.

To transform the Domain result within the Resonder you have multiple possibilities, like manual mapping or league/fractal or selective/transformer or maybe laminas/laminas-hydrator. It really depends on your specific use case.

1 Like

Hi Odan,

That makes a lot of sense. I’ll give the UserCreateResponder class some thought and see if I can get somewhere with it.

I have a specific idea for a project in mind so I’ll probably be asking lots more questions :wink:

Thank you

Hi,

I added ResponseFactoryInterface and RouteParserInterface to the container and used the Responder in your repo. Invoked the responder in UserCreateAction and that did the trick. I don’t need a custom UserCreateResponder just yet.

Thank you!

1 Like