100,count=>1 * @example $counter = new Counter(null,true); - this instantiates the $counter object and sets the initial counter [page] => 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'],[count] => 1, [time] => 789 * */ class Counter { var $page; var $count; var $timer; /** * Constructor * * @param string $page - if no page is given, the default will be set (server_name + request_uri) * @param bool $timer - set to true if you want to start the timer on instantiation */ function __construct($page=null,$timer=false){ $this->setPage($page); $this->addCount($page); if($timer == true){ $this->startTimer(); } } /** * Sets the page * * @param string $page */ private function setPage($page){ $this->page = is_null($page) ? 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : $page; } /** * Starts the timer if a timer does NOT already exist in session * */ protected function startTimer($restart = false){ session_start(); $this->timer = true; $this->sid = session_id(); $_SESSION['start-'.$this->page] = !array_key_exists('start-'.$this->page,$_SESSION) || $restart == true ? time() : $_SESSION['start-'.$this->page]; } /** * Forces a restart of the timer * */ public function restartTimer(){ $this->startTimer(true); } /** * Stops the timer if there is not already a stop value in session * */ public function stopTimer(){ $_SESSION['stop-'.$this->page] = array_key_exists('stop-'.$this->page,$_SESSION) ? $_SESSION['stop-'.$this->page] : time(); } /** * Returns an array of all counts for the object * * @return array */ public function getAllCounts(){ $tmp = array(); $tmp['page'] = $this->getPage(); $tmp['count'] = $this->getCount(); if($this->timer){ $tmp['time'] = $this->getTime(); } return $tmp; } /** * Getter method for the page var * * @return unknown */ public function getPage(){ return $this->page ? $this->page : null; } /** * Getter method for the count * * @return unknown */ public function getCount(){ return $this->count; } /** * Getter method for the time. Looks to see if there is a stop time in session * * @return unknown */ public function getTime(){ $stop_at = array_key_exists('stop-'.$this->page,$_SESSION) ? $_SESSION['stop-'.$this->page] : time(); return round($stop_at - $_SESSION['start-'.$this->page]); } /** * Add 1 to the count * * @param string $page */ public function addCount($page=null){ $this->setPage($page); if($this->getPage()){ $this->count++; } } /** * Subtract 1 from the count * * @param string $page */ public function subCount($page=null){ $this->setPage($page); if($this->getPage()){ $this->count--; } } } ?>