Object Oriented programming - a practical design example
Archive - Originally posted on "The Horse's Mouth" - 2009-08-27 17:30:35 - Graham Ellis
Object Oriented coding makes enormous sense when you're looking at a medium sized or larger application - but it's a complete change of thought process for the traditional structured programmer.
We ran an Object Oriented Programming in PHP course today, and the course concluded with me taking some sample data - web access logs - and starting to specify the classes suited for handling thet data for a variety of reports. Source code is [here].
You'll see that the example is all in a single file. Yes - it is, but that's just for initial testing; the first program is really no more than a test harness to make sure I have the object descriptions right. Before a program based on these classes went live, the classes would be split out into a separate required file ... but NOT to three separate files, as would be the case with a Java application.
As we read in records from the log file, we have to interpret them to make up visit objects. The "bull at a gate" approach to that would be to analyse the records in the main code, at least until we knew what type of object we were going to create. However, I have chosen to code a utility (factory) method within the code that will be within the class file - that way, the analysis code will be shareable between many programs, and will be hidden within (encapsulated in) the class structure. It all leads to a very simple main program file:
$rtab = array();
foreach (file("../weekend/ac_20090522") as $lyne) {
if ($obj = addrecord($lyne)) {
$current_ip = $obj->getip();
if (! $rtab[$current_ip]) {
$rtab[$current_ip] = $obj;
} else {
$rtab[$current_ip]->merge($obj);
}
}
}