简体   繁体   中英

Override Yii2 Class

Assuming yii2-app-advanced. I would like to override the base implementation of \\yii\\helpers\\Inflector::hasIntl() which is used (indirectly) by yii\\web\\Response .

original code

protected static function hasIntl()
{
    return extension_loaded('intl');
}

the code I want

<?php

namespace backend\components;

class Inflector extends \yii\helpers\Inflector
{
    protected static function hasIntl()
    {
        return false;
    }
}

So, I create backend\\components\\Inflector extending yii\\helpers\\Inflector and override the method as shown above.

Then in backend/config/bootstrap.php I add:

Yii::$container->set('\yii\helpers\Inflector', '\backend\components\Inflector');

But is not using the custom implementation. It keeps using the original one. So, questions:

  • why is not working?
  • a good alternative solution? (a posted an ugly one)

I have read Yii2 extend or replace core class and used this Yii::$container->set method before, but in this case is not working, even if done like:

Yii::$container->set('\yii\helpers\Inflector', [
    'class' => '\backend\components\Inflector',
]);

官方文档证实了这种方法,但类映射看起来有点不同:

Yii::$classMap['yii\helpers\Inflector'] = '@app/components/Inflector.php';

I don't consider this an elegant solution

I was able to solve it by using:

Yii::$classMap['yii\helpers\Inflector'] = '@path/to/new/file'

But this doesn't looks as elegant as the other solution, as is replacing the file. In this case the new file have to have the original namespace yii\\helpers\\Inflector and extend yii\\helpers\\BaseInflector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM