)]}',
<?php // . . . $config = [ // . . . 'components' => [ // . . . 'response' => [ 'formatters' => [ 'jsonvp' => 'app\components\JsonVpResponseFormatter', ], ], ], // . . . ];
yii\web\Response
there is a property $formatters
, which will be complemented by what is in the configuration. And now, if in some action set Yii::$app->response->format = 'jsonvp';
then it will use the app\components\JsonVpResponseFormatter
class for formatting the response. In the framework, there is an interface yii\web\ResponseFormatterInterface
that governs the rules for writing such classes, so you can apply this interface to my new class. <?php namespace app\components; use yii\helpers\Json; use yii\web\Response; use yii\web\ResponseFormatterInterface; class JsonVpResponseFormatter implements ResponseFormatterInterface { /** * Format as Vulnerability Protected JSON. * @param Response $response */ public function format($response) { $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8'); if ($response->data !== null) { $response->content = ")]}',\n" . Json::encode($response->data); } } }
<?php namespace app\controllers; use Yii; use yii\web\Controller; /** * site/* actions. * @package app\controllers */ class SiteController extends Controller { /** * Test JSON output * @return array */ public function actionJson() { Yii::$app->response->format = 'jsonvp'; return ['123', '456']; } }
localhost/index.php?r=site/json
localhost/index.php?r=site/json
in the browser displays the following result: )]}', ["123","456"]
Source: https://habr.com/ru/post/256213/
All Articles