Yii2:如何访问模块内部的模块变量?

I'm creating a Yii2 Module , in this module I set a variable upload_path. now I'm trying to access this variable from a behavior inside this module using

 module = MyModuleClass::getInstance();

and I get null , the only way to access this variable is by setting the config :

'modules' => [
    'w_forms' => [
        'class' => 'wardany\dform\DynamicForm',
        'upload_path'=> "@frontend/web/uploads",
        'upload_url'=> "/uploads",
    ],
]

Yii::$app->getModule('w_forms')->upload_path

but I think this is not good cuz user may change the Id 'w_forms'

ofcourse you will get null value.

I think using MyModuleClass::getInstance(); will create a new instance of your class but yii creates its own instance of the module on the begining of the app.

you can use $this->upload_path inside the module.

and using $this->owner->upload_path inside the behavior to access its parents properties.

One solution is to put them in your Application's Yii::$app->params.

Pros:

  • You will always be able to access them even if the Module is not instantiated yet.
  • You will be able to access the parameters even from your Module's ActiveRecords.

Cons:

  • You will need to have a fixed key in your parameters so you cannot configure individual modules.

You can inherit all Controllers from a single controller and add variable to parent controller

Main controller:

<?php

namespace frontend\modules\api\controllers;

use yii\web\Controller;

/**
 * Default controller for the `default` module
 */
class DefaultController extends Controller
{
    public $someVar=255;
}

Inherited controller:

     namespace frontend\modules\api\controllers;

    class SomeController extends DefaultController 
    {
        public function actionIndex() {
              $someVariable=$this->someVar;
         }
    }