Automatic view counting in Yii

Site has moved

This site has moved to a new location. Visit the new site at http://programsdream.nl.

By Ronald van Belzen | April 28, 2013

A simple method to automatically count the number of times that an item has been viewed in Yii is with the aid of scenario's.

In the controller that accesses the model the scenario is set:

$model = BlogPost::model();
$model->scenario = 'view';

While in the model the afterFind() function is overwritten:

protected function afterFind() {
  if(self::model()->scenario == 'view') {
    $this->viewed++;
    $this->save();
  }
  return parent::afterFind();
}

Of course, model events that trigger upon saving need to take into account that in the scenario "view" the afterFind event performs a save.