When building an API it is common for people to just grab stuff from the database and pass it to json_encode(). The problem with this approach is that it can quickly lead to inconsistent output - for example when a database table schema changes.
A data transformer acts as the middle-man between the data fetched and what is output to ensure consistency. Think of it as a view layer for your data. Below is a transformer class and example that you can extend to write your own transformers.
Now let's create a specific transformer for outputting a user's data.
And finally we call the user transformer from our controller, passing in the user's data and outputting as JSON.
If you use Laravel or Lumen an extra method that I use in my Transformer class is response:
Then in my controller I can just return $transform->response(201); to get a JSON response with a 201 status code for example.