There are several controllers. It is necessary that, before processing them, some script should work, in which, in case of passing the condition, redirect worked.

I tried to implement a trace. way

In the frontend / config / main.php, the BeforeController component added to the bootstrap field BeforeController

 'bootstrap' => ['log','BeforeController'], 

BeforeController itself:

 class BeforeController extends \yii\base\Component { public function init() { if(Yii::$app->user->isGuest) return parent::init(); $user = User::findOne(Yii::$app->user->id); if(!$user->phone_confirmed_at) return Yii::$app->response->redirect(['sms/activate']); return parent::init(); } } 

The problem is that if you refresh the sms/activate page, there will be a permanent redirect. But do something like:

 if(Yii::$app->controller->id == 'sms') return true; 

I can not, because In the controller, we have not yet hit. What are the alternatives to this solution?

    2 answers 2

    1. You can create a controller in which to write your code in the beforeAction method. And all controllers inherit from it. Yii :: $ app-> controller-> id will be available there.
    2. In your example, check with Yii::$app->request->baseUrl == 'sms/activate'

    3. Register in the config:

      return [... 'on beforeAction' => function ($ event) {...}];

    • Not quite suitable, because There are controllers that are inherited from the controllers from the vendor folder. - Radik Kamalov
    • Well, if you have all controllers inherited from yii\web\Controller , then create your own, inherit from yii\web\Controller and you will have it as the base one. Otherwise, you can create a treyt with the beforeAction method and connect it in all controllers - OlyLad
    • Not all inherit from yii \ web \ Controller. Regarding the traits, I would rather stop on this variant - Radik Kamalov

    You can use the magic method __construct in each such controller. First there will be a test of this method, then everything that is in the controller.

    • duplicate code? - Radik Kamalov
    • Put the code in one place, and in constructors just call it. - SOFQ3 4:34 pm