I have defined a custom response class and was trying to use it in a module.
In the controller action i return an array of results, but the custom response class isn't used.
Instead, the class used is the default yii\web\Response
My implementation
The module configuration in 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',
],
],
],
In the controller i edited the behaviors method:
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;
}
In the action if i do:
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;
}
I get this result (as expected from yii\web\Response):
[
{
"id": 1,
"name": "John",
"surname": "Davis"
},
{
"id": 2,
"name": "Marie",
"surname": "Baker"
},
{
"id": 3,
"name": "Albert",
"surname": "Bale"
}
]
But if i change the action to this:
$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;
Then i get the expected result, which is this:
{
"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"
}
]}
It seems the behaviors i defined aren't doing anything.
What do i need to do to just return the array in the action and the custom response component is used?
Thanks in advance