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