How to set up a unique class of module in yii-2? Interested in the option without creating in the GII system.

This is a class that inherits from yii\base\Module

An example of how this class might look like:

 namespace app\modules\forum; class Module extends \yii\base\Module { public function init() { parent::init(); $this->params['foo'] = 'bar'; // ... ΠΎΡΡ‚Π°Π»ΡŒΠ½ΠΎΠΉ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΡŽΡ‰ΠΈΠΉ ΠΊΠΎΠ΄ ... } } 

Question: What exactly should the init() function do?


Here is another option to customize this class:

If the init () method has become too cumbersome because of the code that sets the properties of the module, these properties can be saved as a configuration and then loaded into the init () method as follows:

 public function init() { parent::init(); // инициализация модуля с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ ΠΊΠΎΠ½Ρ„ΠΈΠ³ΡƒΡ€Π°Ρ†ΠΈΠΈ, Π·Π°Π³Ρ€ΡƒΠΆΠ΅Π½Π½ΠΎΠΉ ΠΈΠ· config.php \Yii::configure($this, require(__DIR__ . '/config.php')); } 

At the same time in the configuration file config.php there may be the following code similar to the configuration of the application:

 <?php return [ 'components' => [ // список ΠΊΠΎΠ½Ρ„ΠΈΠ³ΡƒΡ€Π°Ρ†ΠΈΠΉ ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ‚ΠΎΠ² ], 'params' => [ // список ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ² ], **]; 

Question: What exactly should there be - components and params ?

    1 answer 1

    Here it can be, but it should not be, similar settings that we did in config/web.php

    Personally, I have added here

     return [ 'components' => [ // список ΠΊΠΎΠ½Ρ„ΠΈΠ³ΡƒΡ€Π°Ρ†ΠΈΠΉ ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ‚ΠΎΠ² // пСрСопрСдСляСм layout ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ. (Π’Π΅ΠΏΠ΅Ρ€ΡŒ ΠΏΡ€ΠΈ Π²Ρ‹Π·ΠΎΠ²Π΅ модуля, Π±ΡƒΠ΄Π΅Ρ‚ Π²Ρ‹Π·Ρ‹Π²Π°Ρ‚ΡŒΡΡ Π΄Ρ€ΡƒΠ³ΠΎΠΉ шаблон, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Ρ€Π°Π·ΠΌΠ΅Ρ‰Ρ‘Π½ ΠΈΠΌΠ΅Π½Π½ΠΎ Π² самом ΠΌΠΎΠ΄ΡƒΠ»Π΅. 'layout' => 'main.php', ], 'params' => [ // список ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ² ], ]; 

    And we specify the path to the configuration file of the module itself (it is also better to create it in the module itself, in the config folder, at the level of a unique module class):

     Yii::configure($this, require(__DIR__ . '/config.php'));