I defined a custom response class and tried to use it in a module.
In the controller action, I return an array of results, but the custom response class is not used.
Instead, the default yii \ web \ Response is used.
My implementation
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 behavior method:
public function behaviors() { $behaviors = parent::behaviors(); $behaviors['contentNegotiator'] = [ 'class' => 'yii\filters\ContentNegotiator', 'response' => $this->module->get('response'), 'formats' => [
In 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 changed the action to this:
$dataList = [ ['id' => 1, 'name' => 'John', 'surname' => 'Davis'], ['id' => 2, 'name' => 'Marie', 'surname' => 'Baker'], ['id' => 3, 'name' => 'Albert', 'surname' => 'Bale'], ];
Then I get the expected result, which is as follows:
{ "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 that the behavior that I defined does nothing.
What do I need to do to just get the array back into action and use the custom response component?
Thank you in advance