5
我已经定义了自定义响应类,并试图在模块中使用它。Yii2模块自定义响应类
在控制器操作中,我返回一个结果数组,但不使用自定义响应类。
相反,所用的类是缺省YII \网络\响应
我的实现
在配置/ 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',
],
],
],
在控制器我编辑行为方法:
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;
}
在行动,如果我做的:
public function actionIndex() {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$dataList = [
['id' => 1, 'name' => 'John', 'surname' => 'Davis'],
['id' => 2, 'name' => 'Marie', 'surname' => 'Baker'],
['id' => 3, 'name' => 'Albert', 'surname' => 'Bale'],
];
return $dataList;
}
我得到这样的结果(从警予\网络\响应预期):
[
{
"id": 1,
"name": "John",
"surname": "Davis"
},
{
"id": 2,
"name": "Marie",
"surname": "Baker"
},
{
"id": 3,
"name": "Albert",
"surname": "Bale"
}
]
但是,如果我改变行动在:
$dataList = [
['id' => 1, 'name' => 'John', 'surname' => 'Davis'],
['id' => 2, 'name' => 'Marie', 'surname' => 'Baker'],
['id' => 3, 'name' => 'Albert', 'surname' => 'Bale'],
];
//return $dataList;
$resp = $this->module->get('response'); //getting the response component from the module configuration
$resp->data = $dataList;
return $resp;
然后我得到预期的结果,这是这样的:
{
"status": {
"response_code": 0,
"response_message": "OK",
"response_extra": null
},
"data": [
{
"id": 1,
"name": "John",
"surname": "Davis"
},
{
"id": 2,
"name": "Marie",
"surname": "Baker"
},
{
"id": 3,
"name": "Albert",
"surname": "Bale"
}
]}
看来我定义的行为没有做任何事情。
我需要做些什么才能在操作中返回数组并使用自定义响应组件?
在此先感谢
是的,我不想通过模块取代了应用程序的响应组件。 只需在模块中使用自定义响应组件。 谢谢! – Jepi
@Jepi然后使用第一个选项。如果您将应用程序响应组件替换为模块的init函数,那么它只会影响您的模块。要替换整个应用程序中的某个组件(包括其他组件),应该在引导过程中进行替换 – oakymax
@Jepi我的意思是父应用程序可能已经实现了响应组件。例如,可以启动一些用于所有模块通用的记录或调试的服务。通过替换模块内的组件,您完全阻止了在父应用程序中为您的模块定制此组件的功能。因此,如果您希望您的模块将用于其他应用程序,请记住 – oakymax