我已经定义了一个自定义响应类,并试图在模块中使用它.
在控制器操作中,我返回一个结果数组,但不使用自定义响应类.
相反,使用的类是默认的yii\web\Response
我的实施
config/web.php中的模块配置:
'mymodule' => [
'class' => 'app\modules\mymod\Mymod',
'components' => [
'response' => [
'class' => 'app\modules\mymod\components\apiResponse\ApiResponse',
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
],
],
],
Run Code Online (Sandbox Code Playgroud)
在控制器中我编辑了行为方法:
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator'] = [
'class' => 'yii\filters\ContentNegotiator',
'response' => $this->module->get('response'),
'formats' => [ //supported formats
'application/json' => \yii\web\Response::FORMAT_JSON,
],
];
return $behaviors;
}
Run Code Online (Sandbox Code Playgroud)
在行动中,如果我这样做:
public function actionIndex() {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$dataList = [
['id' => 1, 'name' => 'John', 'surname' => 'Davis'],
['id' …Run Code Online (Sandbox Code Playgroud)