1

I want to get controller id and its action in my component which is a bootstrap component , but Yii::$app->controller is null when component is run , I think this is due to running before controller runs .

How can get controller id in my bootstrap component ?

or is there another way to run a task after any controllers ? component file :

namespace common\components;

use yii;

use common\models\Statistic;

class ActivityLogs extends \yii\base\Component
{
    public function init() {

        Yii::error(Yii::$app->controller->id); 
        // Yii::$app->controller is null 

        parent::init();
    }
}

config file :

'bootstrap' => ['log', 'ActivityLogs'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
    'user' => [
        'identityClass' => 'common\models\User',
        'enableAutoLogin' => true,
    ],
    'ActivityLogs'=>[
        'class' => 'common\components\ActivityLogs'
    ],

thanks before .

Masoud Aghaei
  • 1,113
  • 2
  • 15
  • 27

1 Answers1

1

I think is null because you are in bootstrap phase and at this moment the controller instance is not yet availaible .

I suggest you of don't perform this in init() function ..

but you can use your proper activityLogs statics functions when the application startup phase is terminated ..then the controller is properly defined .

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • I mentioned that controller is null so controller->id throw a Trying to get property of non-object error . I can get controller id where ever in application but not in component body . – Masoud Aghaei Feb 12 '16 at 18:27
  • Just add if statement checking if Yii::$app->controller is object and then perform desired action. Though you will have to do it somwhere else than init() as it only fires during app initialization when there's no controller assigned. – xReprisal Feb 14 '16 at 10:13