PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 3 ■ OBJECT BASICS


public $numPages;
public $title;
public $producerMainName;
public $producerFirstName;
public $price;


function __construct( $title, $firstName,
$mainName, $price,
$numPages ) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
$this->numPages = $numPages;
}


function getNumberOfPages() {
return $this->numPages;
}


function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
$base .= ": page count - {$this->numPages}";
return $base;
}


function getProducer() {
return "{$this->producerFirstName}".
" {$this->producerMainName}";
}
}


I have addressed the complexity issue, but at a cost. I can now create a getSummaryLine() method for
each format without having to test a flag. Neither class maintains fields or methods that are not relevant
to it.
The cost lies in duplication. The getProducerName() method is exactly the same in each class. Each
constructor sets a number of identical properties in the same way. This is another unpleasant odor you
should train yourself to sniff out.
If I need the getProducer() methods to behave identically for each class, any changes I make to one
implementation will need to be made for the other. Without care, the classes will soon slip out of
synchronization.
Even if I am confident that I can maintain the duplication, my worries are not over. I now have two
types rather than one.
Remember the ShopProductWriter class? Its write() method is designed to work with a single type:
ShopProduct. How can I amend this to work as before? I could remove the class type hint from the
method declaration, but then I must trust to luck that write() is passed an object of the correct type. I
could add my own type checking code to the body of the method:


class ShopProductWriter {
public function write( $shopProduct ) {
if (! ( $shopProduct instanceof CdProduct ) &&
! ( $shopProduct instanceof BookProduct ) ) {
die( "wrong type supplied" );

Free download pdf