Tracking data for every request in Yii2
What's the best place in the code to track the date of the user's last visit, or any data that should be tracked on every application request? Is it a good idea to extend yii \ web \ Controller?
You can use a basic controller and of course it's a good idea. But there is another more elegant approach. You can do the following:
1 . Add the component to the component catalog, for example ( MyTrackingClass
):
namespace app\components;
class MyTrackingClass extends \yii\base\Component{
public function init() {
//SOME CODE HERE
//SOME CODE HERE
//SOME CODE HERE
parent::init();
}
}
2 . Add the component MyTrackingClass
to your component array in the config file:
'components' => [
'MyTrackingClass'=>[
'class'=>'app\components\MyTrackingClass'
],
//other components
3 - add MyTrackingClass
to array bootstarp
in config file:
'bootstrap' => ['log','MyTrackingClass'],
Now you can see everything that you have written in your method init()
will be performed on every request for each module
, controller
, action
and so on ...
Note, if you don't need to use Events
and Behaviors
, you can use \yii\base\Object
instead\yii\base\Component