Masoud Aghaei
Masoud Aghaei

Reputation: 1221

get controller id in Yii2 bootstrap component

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 .

Upvotes: 1

Views: 643

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133370

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 .

Upvotes: 1

Related Questions