Demonstation of Page View Counter using Memcache

Page Views : 2

If you need to count page or object views updating a database with each view increment could be a big load increase for your server, an effective solution with PHP is using memcache. The following demonstration uses my memcache PHP and MYSQL wrapper class to update a memcache key that holds holds the counter data i.e. for a page, or object view. A threshold can be manually set that will write the count value to the database when required i.e. in this example after 10 views. The database value is also used to keep the counter in sync should the memcache server be restarted or not available. You can emulate this by clicking the disable cached query button, you will see the counter value reverts to the last database value.




The counter increment function looks like this, note the use of $_notify_mysql_interval to set the DB update interval :

private function incrementObjectViewCount($_objectID,$_dbObjectViewCount)
{
	$_cacheConnected=$this->__cache->get('memcacheconnected');
	
	// if memcache disabled return db value
	if (!$_cacheConnected) { return $_dbObjectViewCount; }
	
	$_key = 'object-'. $_objectID. '-counter';

	if(!$this->__cache->cacheGet($_key)) {
		// create cache key using db value
		$this->__cache->cacheSet($_key, $_dbObjectViewCount,0);
	}

	$_count=$this->__cache->increment($_key);
	
	// reset cached count if db count is greater
	if ($_count < $_dbObjectViewCount) { $this->__cache->cacheSet($_key, $_dbObjectViewCount,0); }

	$_notify_mysql_interval = 10;
	if($_count % $_notify_mysql_interval == 0) {
	
		// update database with new count value
		$_query="UPDATE counter SET viewCounter = '". $_count. "' WHERE id='".$_objectID."'";
			$_result=mysql_query($_query);
				if (!$_result) throw new Exception("Query failed: " . mysql_error().' - '. $_query);			

	}

	return $_count;	
}