Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - Change headers collection

Tags:

php

yii2

I want to change the default headers collection in my RESTful api. I can change the header with set() method on every response that I send, but i don't want to write

$response = Yii::$app->response;
$response->headers->set('X-Powered-By','My server <devel>')
$response->setStatusCode(somecode);
$response->data = somedata;

return $response;

This is quite cumbersome and my Controller actions grow at length, as i have to respond to every bad request and error. I have tried to change the response component in rest/config/main.php, but I am forbidden to change headers property, as it is read-only.

  • The setStatusCode() method is quite useful, as it returns the status text automatically.

Please help.

like image 332
macmilan Avatar asked Feb 08 '23 07:02

macmilan


1 Answers

You don't need to go to the trouble of extending the response class. You can do this by configuring the response component of the application and adding custom headers in the beforeSend event, e.g.:

return [
    ...
    'components' => [
        ...
        'response' => [
            'on beforeSend' => function($event) {
                $event->sender->headers->add('X-Frame-Options', 'DENY');
            },
        ],
        ...
    ],
];

This will add the header(s) for all responses. If you want to do it per controller, you can use \Yii::$app->response->headers->add($name, $value); in the afterAction() method of the controller.

like image 126
spikyjt Avatar answered Feb 10 '23 09:02

spikyjt