As was mentioned at the beginning of this chapter, the last stage of processing the data before sending it to the client is passing it through the response formatter. Anything that the controller action returned is wrapped into the Response
object, which decides how to ultimately send the data down the pipe. Let's see how we can utilize a custom response formatter for our purposes.
Probably the most obvious use of the custom response formatter is returning the JSON data for a given route. The following is a throwaway snippet of the exploratory code, which returns the list of attributes of the registered services from the database:
public function actionJson() { $models = ServiceRecord::find()->all(); $data = array_map(function ($model) {return $model->attributes;}, $models); $response = Yii::$app->response; $response->format = Response::FORMAT_JSON; $response->data = $data; return $response...