PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 9 ■ GENERATING OBJECTS


const MEGA = 2;
private $mode = 1;


function __construct( $mode ) {
$this->mode = $mode;
}


function getApptEncoder() {
switch ( $this->mode ) {
case ( self::MEGA ):
return new MegaApptEncoder();
default:
return new BloggsApptEncoder();
}
}
}


$comms = new CommsManager( CommsManager::MEGA );
$apptEncoder = $comms->getApptEncoder();
print $apptEncoder->encode();


I use constant flags to define two modes in which the script might be run: MEGA and BLOGGS. I use a
switch statement in the getApptEncoder() method to test the $mode property and instantiate the
appropriate implementation of ApptEncoder.
There is little wrong with this approach. Conditionals are sometimes considered examples of bad
“code smells,” but object creation often requires a conditional at some point. You should be less
sanguine if you see duplicate conditionals creeping into our code. The CommsManager class provides
functionality for communicating calendar data. Imagine that the protocols we work with require you to
provide header and footer data to delineate each appointment. I can extend the previous example to
support a getHeaderText() method:


class CommsManager {
const BLOGGS = 1;
const MEGA = 2;
private $mode ;


function __construct( $mode ) {
$this->mode = $mode;
}


function getHeaderText() {
switch ( $this->mode ) {
case ( self::MEGA ):
return "MegaCal header\n";
default:
return "BloggsCal header\n";
}
}
function getApptEncoder() {
switch ( $this->mode ) {
case ( self::MEGA ):
return new MegaApptEncoder();
default:
return new BloggsApptEncoder();

Free download pdf