Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^24) CHAPTER 3 ■ SINGLETON AND FACTORY PATTERNS
decide which class should be instantiated, based on application logic or a configuration setting.
For example, you could use such a provider to extend a class without needing to refactor any
other part of the application to use the new extended name.
Typically, a factory pattern has one key ingredient: a static method, which is by convention
named factory. However, this is merely a convention, and a factory method may be given any
name. The static method may take any number of arguments and must return an object.
Listing 3-4 demonstrates the most basic possible factory class.
Listing 3-4. Creating a Basic Factory
class MyObject {
//Your object that will be returned from the factory
}
class MyFactory {
public static function factory() {
//Return a new instance of your object
return new MyObject();
}
}
The factory would then be invoked like this:
$instance = MyFactory::factory();
Well, that’s nice, but unfortunately, totally useless. It’s time to examine a couple of real-
world scenarios where you might employ a factory.


The Image Factory


Picture, if you will, a drawing program. You want to be able to draw an image contained in a file
to the screen. Each image file is in a totally different file format and it is not appropriate to place
image-parsing code for every conceivable image type in a single class. In this case, you will need
to create a class for each image type: Image_PNG, Image_JPEG, and so on. Each class should be
contained in a separate file. All of these image classes should contain a few common methods
to get the image height, width, and raw image data. However, how they each parse their files to
get this information will differ greatly. You can use an interface to define the common func-
tionality and create a factory pattern to make your API easier to use, as shown in Listing 3-5.

Listing 3-5. Image File Parsing with Factories

interface IImage {

function getHeight();
function getWidth();
function getData();

}

McArthur_819-9C03.fm Page 24 Friday, February 1, 2008 10:24 AM

Free download pdf