Quantcast
Channel: User bdsl - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by bdsl for PHP Counter Using OOP

$
0
0
  • Use UpperCamelCase for class names. LogFile, not LOGFILE. When you have a variable and the most interesting thing about it is that it's expected to hold a reference to something that is_aLogFile you should name it logFile.
  • Use lowerCamelCase for functions. read and write, not READ and WRITE
  • No spaces around the arrow operator
  • Code after a return statement in a method can never be reached, so delete it.
  • read() does not use the handle returned by fopen, so don't call fopen
  • the temp variable $freed doesn't help us understand the code, so we can lose it
  • read is a slightly unconventional name. If we rename the function to getCount it will be more obvious what it does.
  • You said you wanted to make a hit counter. So rename the class from LogFile to HitCounter, and the variable to hitCounter
  • the $FileData parameter to write doesn't get used because the variable is re-assigned inside the function. We can lose it.
  • The write method is supposed to add one to the number in the file. Write doesn't really express that. Rename it to increment.
  • Use a blank line between functions. The procedural code at the end should generally be in a separate file, but here we can just add a couple of extra lines. Delete the blanks between the last three lines of code.
  • Don't repeat yourself - we shouldn't have to mention 'counter.txt' more than once. OOP is all about combining data structures and behaviour into classes, so make a class private variable to hold the filename, and pass it via a constructor
  • $fread doesn't exist in the scope of increment, so we can't use it. This won't work. Replace it with a call to to getCount()
  • Swap the first two lines of increment, so we're not doing two concurent accesses to the same file, although we might be running inside a server that's running our script twice and still doing two concurrent accesses.
  • Rename the variable $FileData to $count, since that's what it is.
  • Replace the fopen,fwrite,fclose sequence with file_put_contents, since that does the same thing and is more succinct.
    • We need tag, since our php code continues to the end of the file.

That leaves us with:

<?phpclass HitCounter {    private $fileName;    public function __construct($fileName){      $this->fileName = $fileName;    }    public function getCount() {        return file_get_contents($this->fileName);    }    public function increment() {        $count = $this->getCount() + 1;        file_put_contents($this->fileName, $count);    }}$hitCounter = new HitCounter("counter.txt");    $hitCounter->increment();    echo $hitCounter->getCount();

Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>