PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 10 ■ PATTERNS FOR FLEXIBLE OBJECT PROGRAMMING


function getNameFromLine( $line ) {
if ( preg_match( "/.-(.)\s\d+/", $line, $array ) ) {
return strreplace( '',' ', $array[1] );
}
return '';
}


function getIDFromLine( $line ) {
if ( preg_match( "/^(\d{1,3})-/", $line, $array ) ) {
return $array[1];
}
return -1;
}


class Product {
public $id;
public $name;
function __construct( $id, $name ) {
$this->id = $id;
$this->name = $name;
}
}


Let’s imagine that the internals of this code to be more complicated than they actually are, and that
I am stuck with using it rather than rewriting it from scratch. In order to turn a file that contains lines like


234-ladies_jumper 55
532-gents_hat 44


into an array of objects, I must call all of these functions (note that for the sake of brevity I don’t extract
the final number, which represents a price):


$lines = getProductFileLines( 'test.txt' );
$objects = array();
foreach ( $lines as $line ) {
$id = getIDFromLine( $line );
$name = getNameFromLine( $line );
$objects[$id] = getProductObjectFromID( $id, $name );
}


If I call these functions directly like this throughout my project, my code will become tightly wound
into the subsystem it is using. This could cause problems if the subsystem changes or if I decide to
switch it out entirely. I really need to introduce a gateway between the system and the rest of our code.


Implementation


Here is a simple class that provides an interface to the procedural code you encountered in the previous
section:


class ProductFacade {
private $products = array();


function __construct( $file ) {
$this->file = $file;
$this->compile();

Free download pdf