PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

■Chapter 6: Objects and Design ......................................................................................................


In this chapter, I will examine some issues that might influence a few of these choices.

Object-Oriented and Procedural Programming


How does object-oriented design differ from the more traditional procedural code? It is tempting to say
that the primary distinction is that object-oriented code has objects in it. This is neither true nor useful.
In PHP, you will often find procedural code using objects. You may also come across classes that contain
tracts of procedural code. The presence of classes does not guarantee object-oriented design, even in a
language like Java, which forces you to do most things inside a class.
One core difference between object-oriented and procedural code can be found in the way that
responsibility is distributed. Procedural code takes the form of a sequential series of commands and
method calls. The controlling code tends to take responsibility for handling differing conditions. This
top-down control can result in the development of duplications and dependencies across a project.
Object-oriented code tries to minimize these dependencies by moving responsibility for handling tasks
away from client code and toward the objects in the system.
In this section I’ll set up a simple problem and then analyze it in terms of both object-oriented and
procedural code to illustrate these points. My project is to build a quick tool for reading from and writing
to configuration files. In order to maintain focus on the structures of the code, I will omit
implementation details in these examples.
I’ll begin with a procedural approach to this problem. To start with, I will read and write text in the
format


key:value


I need only two functions for this purpose:

function readParams( $sourceFile ) {
$prams = array();
// read text parameters from $sourceFile
return $prams;
}


function writeParams( $params, $sourceFile ) {
// write text parameters to $sourceFile
}


The readParams() function requires the name of a source file. It attempts to open it, and reads each
line, looking for key/value pairs. It builds up an associative array as it goes. Finally, it returns the array to
the controlling code. writeParams() accepts an associative array and the path to a source file. It loops
through the associative array, writing each key/value pair to the file. Here’s some client code that works
with the functions:


$file = "./param.txt";
$array['key1'] = "val1";
$array['key2'] = "val2";
$array['key3'] = "val3";
writeParams( $array, $file ); // array written to file
$output = readParams( $file ); // array read from file
print_r( $output );


This code is relatively compact and should be easy to maintain. The writeParams() is called to create
param.txt and to write to it with something like:

Free download pdf