There is a component configstr that reads from the database the parameters registered in the web.php config

'configstr' => [ 'class' => 'app\components\Configstr', ], 

How can I create a global component instance so that each time I do not call it like this:

 Yii::$app->configstr->second_s 

in this case, it is re-initialized and reads the database again, if you set $ cls_config = new configstr (); then everything is fine once the parameters are loaded from the database. How to make a global instance and where should it be specified?

    2 answers 2

    Make a singleton that will receive data once, save it in static and will not crawl to the database each time. For example, as an option:

     class Cfg { private static $_instance = false; public static function getInstance() { if (false === self::$_instance) { self::$_instance = self::getCfgParams(); } return self::$_instance; } private function __clone() {} private function __construct() {} private static function getCfgParams() { // тут выборка из БД return Model::find()->all(); } } 
    • I didn’t understand much, I need to immediately write a table from the database to the static, in your example, to fill me in, initially, start a method and then use it? - Sergey P
    • $ cfg = Cfg :: getInstance (); in $ cfg will be what you need to get from the database in the getCfgParams () method. In this case, Cfg :: getInstance () can be called several times, there will be only one query to the database. This is the principle of the singletone pattern. - fedornabilkin
    • Thanks, today I will try - Sergey P

    Use Yii::$app->get('configstr')

    Under the hood, Yii2 will add it to the cache.

    And initialize the component in the method init()

    Try it, I think it will work

    • The fact is that in init and filling happens public function init () {parent :: init (); $ this -> _ attributes = ArrayHelper :: map (\ app \ models \ configstr :: find () -> all (), 'name', 'val'); } and if I call as indicated in the question Yii :: $ app-> configstr-> second_s then the init is called and the filling is done again - Sergey P
    • or do you offer another solution? - Sergey P
    • I propose to try instead of Yii::$app->configstr->second_s like this Yii::$app->get('configstr')->second_s (if second_s is an attribute of the component configstr))) - WiRight
    • Anyway, initialization is underway. In the debugger, the query still goes: SHOW FULL COLUMNS FROM configstr why does this query run, I don’t use it exactly, does it also run for all tables? - Sergey P
    • Yes, this query SHOW FULL COLUMNS Yii2 makes under the hood. If you don't mind, could you show the code? Or will I do a mini project and try to reproduce your problem? - WiRight