Fatal Error Class Response not found When Setting Renderer to JSON

Yii 2 App Dev Book Errors chapter 4 errors

In chapter 4 (around pages 95-96) we are shown a throwaway snippet as an example of outputting a view in JSON format which results in a fatal error:

PHP Fatal Error – yii\base\ErrorException Class 'app\controllers\Response' not found

This post is specific to the 'Web Application Development with Yii 2 and PHP' book

The code we are given to set the format within our services controller:

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;

The issue is basically that we haven't defined the route to the Response class so it can be updated in a number of ways.

The best way would be to add the namespace to use at the top of the file with the others and leave the code the same as in the book:

use yii\web\Response;

The full path to the namespace can be defined like this:

$response->format = \yii\web\Response::FORMAT_JSON;

The format can be defined explicitly.

$response->format = 'json';

Whilst looking into this one I came across samdark's repo for the yii2 cookbook which looks like it will be an opensource project rather than the usual packtpub book (in the process of being written).

Response formats in the Yii2 cookbook
Yii2 Cookbook rendered at readthedocs.org

Blog Comments Powered by Disqus