NaturalBornCamper
NaturalBornCamper

Reputation: 3866

Extend Yii2's BaseYii class to add static methods

Is it possible to extend Yii2's BaseYii class, so I could add a static method similar to Yii::t() like this: Yii::my_super_method()?

Can't really find any documentation about that, maybe I missed it.

Upvotes: 3

Views: 582

Answers (2)

rob006
rob006

Reputation: 22174

This is possible by creating own Yii class (for example in root of your project):

require __DIR__ . '/vendor/yiisoft/yii2/BaseYii.php';

class Yii extends \yii\BaseYii
{
    public static function my_super_method() {
        // ...
    }
}

spl_autoload_register(['Yii', 'autoload'], true, true);
Yii::$classMap = require __DIR__ . '/vendor/yiisoft/yii2/classes.php';
Yii::$container = new yii\di\Container();

And loading it in index.php instead core class, by replacing:

require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

with

require __DIR__ . '/../Yii.php';

But if you want only to add a new method you should probably not do this. Overriding core classes in this way is possible, but this is ugly hack and should be avoided whenever possible. It is better to create own helper with this method than to hacking core classes.

Upvotes: 1

vishuB
vishuB

Reputation: 4261

Yes it's possible to extend BaseYii class. show below

namespace app\models;

class ClassName extends \yii\BaseYii
{
     public static function my_super_method()
     {
         ......
         Here your code
         ........ 
     }
}

Now access your method like

app\models\ClassName::my_super_method();

Now access t() method

app\models\ClassName::t();

Upvotes: 0

Related Questions