PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 9 ■ GENERATING OBJECTS


$class = self::$types[$num];
return new $class( $name );
}


function __construct( $name ) {
$this->name = $name;
}
abstract function fire();
}


// new Employee class...


class WellConnected extends Employee {
function fire() {
print "{$this->name}: I'll call my dad\n";
}
}


As you can see, this takes a name string and uses it to instantiate a particular Employee subtype at
random. I can now delegate the details of instantiation to the Employee class’s recruit() method:


$boss = new NastyBoss();
$boss->addEmployee( Employee::recruit( "harry" ) );
$boss->addEmployee( Employee::recruit( "bob" ) );
$boss->addEmployee( Employee::recruit( "mary" ) );


You saw a simple example of such a class in Chapter 4. I placed a static method in the ShopProduct
class called getInstance(). getInstance() is responsible for generating the correct ShopProduct subclass
based on a database query. The ShopProduct class, therefore, has a dual role. It defines the ShopProduct
type, but it also acts as a factory for concrete ShopProduct objects.


■Note I use the term “factory” frequently in this chapter. A factory is a class or method with responsibility for


generating objects.


// class ShopProduct


public static function getInstance( $id, PDO $dbh ) {
$query = "select * from products where id = ?";
$stmt = $dbh->prepare( $query );


if (! $stmt->execute( array( $id ) ) ) {
$error=$dbh->errorInfo();
die( "failed: ".$error[1] );
}


$row = $stmt->fetch( );
if ( empty( $row ) ) { return null; }


if ( $row['type'] == "book" ) {

Free download pdf