Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^26) CHAPTER 3 ■ SINGLETON AND FACTORY PATTERNS
public function getHeight() {
return $this->_height;
}
public function getData() {
return $this->_data;
}
}
class ImageFactory {
public static function factory($file) {
$pathParts = pathinfo($file);
switch(strtolower($pathParts['extension'])) {
case 'jpg':
$ret = new Image_JPEG($file);
break;
case 'png';
$ret = new ImagePNG($file);
break;
default:
//Problem
}
if($ret instanceof IImage) {
return $ret;
} else {
//Problem
}
}
}
Now, when you use the factory method with your image file name, you will get a different
object depending on what type of file you pass in. Since all the Image
* classes implement
IImage, you can use a consistent set of method calls on the returned instance.
$image = ImageFactory::factory('/path/to/my.jpg');
//$image is now an instance of Image_JPEG
echo $image->getWidth();
In the example, ImageFactory is a factory class because it returns a class instance. The type
of class is determined by file extension using the pathinfo() function.
Because it is a factory, the resulting application does not need to know the details of how
these images were parsed. All it needs to know is that each object returned by the factory supports
the IImage interface.
Using this technique makes it significantly easier to consume your API, because it has only
one class and one method. Without the factory pattern, the consumer of your API would need
McArthur_819-9C03.fm Page 26 Friday, February 1, 2008 10:24 AM

Free download pdf