/** * Returns the views count for a specific model. * Note: no bookkeeping record is fine. It means zero impressions... * * @param string $model_name * @param int $model_id * @param bool $unique whether to return the unique count or non unique * * @return int the requested views counter */ public static function getViewsCount($model_name, $model_id, $unique = true) { /* @var PageViewsStat $record */ $record = PageViewsStat::model()->findByAttributes(array('model_id' => $model_id, 'model_name' => $model_name)); if (!$record) { return 0; } if ($unique) { return $record->count_uniq; } return $record->count_non_uniq; }
/** * Loads and returns the 'PageViewsStat' record, based on this->modelClassName and this->modelId. Attempts to create * a new record if none exists. * * @return mixed PageViewsStat or false if failure occurred */ private function _getStatsRecord() { $record = PageViewsStat::model()->findByAttributes(array('model_id' => $this->modelId, 'model_name' => $this->modelClassName)); if (!$record) { // no such record yet. attempt to create it $record = new PageViewsStat(); $record->model_name = $this->modelClassName; $record->model_id = $this->modelId; /* we use try-catch since it could fail due to race condition: from the time when findByAttributes was called * several lines above another process could have done just the same, resulting in this save() failing * due to DB level unique constraint on page_views_stats table. * In this case, try to load the newly born record and use it. */ try { $ret = $record->save(); } catch (CException $e) { // see comment above... . Try to load the fresh record from the DB $record = PageViewsStat::model()->findByAttributes(array('model_id' => $this->modelId, 'model_name' => $this->modelClassName)); if (!$record) { // huston, we have a problem. this wasn't a simple race condition issue but something else. aborting ... Yii::log("Error: couldn't create or load a new PageViewsStat for model class={$this->modelClassName} and model id={$this->modelId}. Cannot continue!", CLogger::LEVEL_ERROR, __METHOD__); return false; } } } return $record; }