PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 9 ■ GENERATING OBJECTS

public function getCommsManager() {
return $this->commsManager;
}
}


The AppConfig class is a standard Singleton. For that reason, I can get an AppConfig instance
anywhere in our system, and I will always get the same one. The init() method is invoked by the class’s
constructor and is therefore only run once in a process. It tests the Settings::$COMMSTYPE property,
instantiating a concrete CommsManager object according to its value. Now my script can get a
CommsManager object and work with it without ever knowing about its concrete implementations or the
concrete classes it generates:


$commsMgr = AppConfig::getInstance()->getCommsManager();
$commsMgr->getApptEncoder()->encode();


Summary


This chapter covered some of the tricks you can use to generate objects. I examined the Singleton
pattern, which provides global access to a single instance. I looked at the Factory Method pattern, which
applies the principle of polymorphism to object generation. I combined Factory Method with the
Abstract Factory pattern to generate creator classes that instantiate sets of related objects. Finally, I
looked at the Prototype pattern and saw how object cloning can allow composition to be used in object
generation.

Free download pdf