1
votes

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',
]);
2
I know nothing about Yii, but here's a related issue if that can help. Looks like you can just define a class yii\helpers\Inflector yourself and have it extend yii\helpers\BaseInflector (which contains the default implementation). Not sure that's what you're looking for (and not sure it even works, but some people mention it). - Jeto
Yes, thanks for the reference. Interesting thread. But he finally don't say where to put the file to do the override. And I don't think is correct to create a class with the same namespace than the original. I'm tying to do the extend version, and tell the framework to use it. - Gabriel Alejandro López López

2 Answers

1
votes

The official documentation confirms this approach, but the class-mapping looks a little different:

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

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.