Yii2 允许控制器内直接返回数组

类似 Laravel 的效果:直接 return 数组输出 JSON 响应。办法有很多,目前我找到的最优解决方案如下。

/**
* Enable JSON response if app returns Array or Object
*
* @return void
*/
protected function enableJsonResponse()
{
    $this->response->on(\yii\web\Response::EVENT_BEFORE_SEND,
        function ($event) {
            /** @var \yii\web\Response $response */
            $response = $event->sender;
            if (is_array($response->data) || is_object($response->data)) {
                $response->format = \yii\web\Response::FORMAT_JSON;
            }
        }
    );
}

或者在配置内定义也可以:

'response' => [
    'on beforeSend' => function ($event) {
        // 回调函数代码如上,同理
    }
    // ...
]
本作品采用《CC 协议》,转载必须注明作者和本文链接
Former WinForm and PHP engineer. Now prefer Golang and Rust, and mainly working on DevSecOps and Kubernetes.
讨论数量: 3

还有官方文档中的用法:

'response' => [
    // ...
    'formatters' => [
        \yii\web\Response::FORMAT_JSON => [
            'class' => 'yii\web\JsonResponseFormatter',
            'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
            'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
            // ...
        ],
    ],
],
4年前 评论
SteveLee

在需要返回的地方加:

\Yii::$app->getResponse()->format = Response::FORMAT_JSON;

也可以

4年前 评论

在Yii中如果要做 API 开发 应该使用继承 rest/Controller 而不是用 web/Controller
你要做的这些框架早就封装在 yii\rest\Serializer 了

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
67
粉丝
590
喜欢
1235
收藏
1133
排名:13
访问:32.4 万
私信
所有博文
社区赞助商