Page 1 of 1

Simple Flat-File Page Counter

Posted: Fri May 25, 2007 7:29 am
by s.dot

Code: Select all

<?php

/*
* SMCounter - Class to generate a flat file based counter
* Distributed freely -- use and redistribute as you wish
* Written: 5-25-2007
*/

class SMCounter
{
	/*
	* Value of our current counter
	* int $current_count
	*/
	var $current_count;
	
	/*
	* Filename of the counter.txt file
	* str $filename
	*/
	var $filename = 'SMCounter.txt';
	
	/*
	* gets the current counter and increments it by 1
	*/
	function get_count()
	{
		$this->current_count = (int) trim(file_get_contents($this->filename));
		return $this->increment_count($this->filename);
	}
	
	/*
	* writes the new incremented counter value
	* and returns the new counter value
	*/
	function increment_count()
	{
		$new_count = $this->get_new_count();
		$this->write_count($new_count);
		return $new_count;
	}
	
	/*
	* increments and returns the value of $this->current_count
	*/
	function get_new_count()
	{
		return $this->current_count + 1;
	}
	
	/*
	* writes the $new_count to the $this->filename
	* @param int $new_count
	*/
	function write_count($new_count)
	{
		$handle = fopen($this->filename, "w");
		flock($handle, LOCK_EX);
		fwrite($handle, $new_count);
		flock($handle, LOCK_UN);
		fclose($handle);
	}
}

?>
Usage:

Code: Select all

<?php
$counter = new SMCounter();
echo $counter->get_count();
I only wrote this simple counter to help me in writing classes (PHP4). I'm having trouble figuring out when I should make a new function to do a task. I could've done all the above in one function, but that's not how classes work, right? Is this class fine?

Posted: Fri May 25, 2007 7:43 am
by Oren
I didn't read the code, but I've see this:

Code: Select all

rtrim(trim(...
Can you explain? Why the hell are you doing rtrim() right after you did trim() :? :? :?: :?:

trim() trims from both the beginning and the end in case you didn't know... there is no point to do rtrim().

Posted: Fri May 25, 2007 7:45 am
by s.dot
Ah, I thought rtrim() removed linefeeds, and trim removed whitespace. I see now that both of them do that.

Posted: Fri May 25, 2007 11:00 am
by Maugrim_The_Reaper
Shift the filename definition to a constructor ;). Then you don't have to edit a file to use an alternate filename (or even multiple files for different pages).