5

I want to extend the class yii\web\Response. So I created a new class Response in the folder components and I try to overwrite the send method.

namespace app\components;

use Yii;

class Response extends \yii\web\Response{

    public function init(){
        parent::init();
    }

    /**
     * Sends the response to the client.
     */
    public function send()
    { ...

Finally I tried to import my new Response-Class by importing it in the config.

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'import'  => [
            'class' => 'app\components\Response',       
        ], 

Why is it not going to work like this?

Philipp
  • 139
  • 1
  • 2
  • 7

1 Answers1

6

Try it like this:

'components' => [
    'response' => [
        'class' => 'app\components\Response',
    ],
Jap Mul
  • 17,398
  • 5
  • 55
  • 66
  • good idea, but this just overrides properties under (Yii::$app) not core classes – Khaled AbuShqear May 22 '16 at 14:46
  • 1
    True, haven't tried it but maybe that works when setting it via the controllerMap http://www.yiiframework.com/doc-2.0/yii-base-module.html#$controllerMap-detail – Jap Mul May 23 '16 at 07:17
  • @Shqear - His answer does override the core class! Your telling it to use `\app\components\Response` instead of `\yii\web\Response`. Mission accomplished as per your Question. If there is something this didn't take care of, then please update your question. In your comment, you said "not core classes". `\yii\web\Response` is a core class, so what else are you needing? Doc on Response: http://www.yiiframework.com/doc-2.0/yii-web-response.html - Response source: https://github.com/yiisoft/yii2/blob/master/framework/web/Response.php – Wade Aug 04 '16 at 05:04
  • @WadeShuler please note that it is not my question, but, i was looking for a way to replace a core class in yii2 with my own without manipulating the source code, so it provides an easy way to override a particuler class to be used in all another core classes that extends it without extend them too, but unfortunately Yii2 doesn't support such thing and it is impossible in current version – Khaled AbuShqear Aug 09 '16 at 21:21
  • @Shqear - I don't exactly understand what you mean by without manipulating source code. You extend ANY core class and place it in say `/components/BaseController.php` and in your normal controllers, those "extend" that class instead of `yii/web/controller/`. You have to change the namespace/path in each controller you want to use it in, else they are pointing to the wrong file. - I don't think what your wanting is possible. Is there any framework that does what you are talking about? – Wade Aug 11 '16 at 19:37