O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #68. Create Objects with Abstract Factories

Use an Abstract Factory pattern to control what type of object is created.

The Abstract Factory pattern is the vending machine of design patterns. You ask it for what you want, and it vends you an object based on your criteria. The value is that you can change what types of objects are created throughout the system by altering just the factory.

The super-simple factory in this example creates Record objects, where each record has an ID, a first name, and a last name. The relationship between these classes is shown in Figure 7-2.

The Record and the RecordFactory classes

Figure 7-2. The Record and the RecordFactory classes

Tip

Factory objects often create more than one type of object. To keep this example simple, though, I've limited the factory to creating only a single object type.

There is no way to strictly enforce that only the factory can create objects of a particular type in PHP. But if you use a factory often enough, engineers copying and pasting your code will end up using the factory; it will quickly become the de facto way of creating the different types of objects.

The Code

Save the code in Example 7-2 as abs_factory.php.

Example 7-2. An Abstract Factory pattern example

<?php class Record { public $id = null; public $first = null; public $last = null; public function __construct( $id, $first, $last ) { $this->id = $id; $this->first = $first; $this->last = $last; } } class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required