Page counter sometimes we need to know the number of the many people who read a page on our website. From page counters, we can also get information about the pages most often read by people. On silverstripe there is no page counters function, so we have to create your own.
To create a page counter is very easy. We just need to create a DataObject that contains two fields namely Counter and Page. Counter Field used to store counter data. Later this DataObject we relate to Page with Page field. Here we create an dataobject separate from page object to avoid versioning page data on each data update.
This Data Object can we save it into a file, for example, let's call the file with a name PageCounter.php in mysite directory.
PageCounter.php
<?
class PageCounter extends DataObject{
static $db = array(
'Counter' => 'Int',
);
static $has_one = array(
'Page' => 'Page',
);
}
?>
Next we just add the following line in the init() function of Page_Controller class in Page.php file.
$pagecounter = DataObject::get_one("PageCounter","PageID='$this->ID'");
if(!$pagecounter){
$pagecounter = new PageCounter();
$pagecounter->PageID=$this->ID;
}
$pagecounter->Counter = $pagecounter->Counter+1;
$pagecounter->write();
Next we must create a function to get value from the page counter object. This function is created inside the Page_Controller class on Page.php file. The goal is only to take counters data.
public function pagecount(){
$pagecounter = DataObject::get_one("PageCounter","PageID='$this->ID'");
return $pagecounter->Counter;
}
This function we can use in our template page.
thanks for the correction. i just correct it.
Simple and works well. Thanks !
Maybe you could submit this snippet to ssbits.com ?
By the way, the code that goes in the init() function has two errors :
- "new PageCounter;" should read "new PageCounter();"
- "$view" should read "$pagecounter"