Juan Borja
Juan Borja

Reputation: 67

Right way to return json in Yii2 controller

I was looking for a answer over the internet and discussed with my partners, but still not sure about the best option to return json in yii2 controller. Here the options:

public function actionExample (){//1
    // do something whit $data result ...
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return $data;
}


public function actionExample (){//2
    // do something whit $data result ...
     echo json_encode($data);

    Yii::$app->end();
}

I think the first option is the best (more elegant) for example for RESTful controller. However, if im not sure if all the calls to controller can receive json, or if some calls are asynchronus maybe the second option is the best, bocause stop the ejecution. I hope some one can explain the diferrence advantages and disadvantages of each method

Upvotes: 4

Views: 6639

Answers (2)

Arbahud Rio Daroyni
Arbahud Rio Daroyni

Reputation: 3783

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;

class ResponseController extends Controller
{
    private $data = array('a', 'b', 'c', 'd', 'e', 'f');

    public function actionResponseJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return [
            'data' => $this->data,
        ];
    }

    public function actionResponseXml()
    {
        Yii::$app->response->format = Response::FORMAT_XML;
        return [
            'data' => $this->data,
        ];
    }

}

Upvotes: 0

rob006
rob006

Reputation: 22174

Controller has dedicated shortcut for this - asJson():

return $this->asJson($data);

But this is equivalent for

$response = Yii::$app->getResponse();
$response->format = Response::FORMAT_JSON;
$response->data = $data;
return $response;

or

Yii::$app->response->format = Response::FORMAT_JSON;
return $data;

So these three options will work the same.


public function actionExample (){//2
    // do something whit $data result ...
     echo json_encode($data);

    Yii::$app->end();
}

This is incorrect - you should not echo in the controller, it may throw an exception in the latest versions of Yii2. It will also not use the correct Content-Type header, so the result may be treated by the client as text/html instead of JSON.

Upvotes: 8

Related Questions