Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.
Popular code excerpts may be moved to "Code Snippets" by the moderators.
<?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);
}
}
?>
<?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?
Last edited by s.dot on Fri May 25, 2007 7:46 am, edited 1 time in total.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Ah, I thought rtrim() removed linefeeds, and trim removed whitespace. I see now that both of them do that.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
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).