简体   繁体   English

覆盖 Yii2 类

[英]Override Yii2 Class

Assuming yii2-app-advanced.假设 yii2-app-advanced。 I would like to override the base implementation of \\yii\\helpers\\Inflector::hasIntl() which is used (indirectly) by yii\\web\\Response .我想覆盖由yii\\web\\Response (间接)使用的\\yii\\helpers\\Inflector::hasIntl()的基本实现。

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.因此,我创建了backend\\components\\Inflector扩展backend\\components\\Inflector yii\\helpers\\Inflector并覆盖了如上所示的方法。

Then in backend/config/bootstrap.php I add:然后在backend/config/bootstrap.php我添加:

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:我之前读过Yii2 扩展或替换核心类并使用过这个Yii::$container->set方法,但在这种情况下不起作用,即使这样做:

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 .在这种情况下,新文件必须具有原始命名空间yii\\helpers\\Inflector并扩展yii\\helpers\\Inflector yii\\helpers\\BaseInflector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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