All Pages All Books|
|
|||
|
®
|
The Factory Pattern 71
The method Assessor::getPropInfo() represents the logical introduction of a PropertyInfo factory as a protected method of the Assessor class. The Assessor::getProperty() method is the public factory that returns one of our three Property subclasses, depending on what property name is requested.
Factories for Lazy Loading
Another significant benefit to using a Factory is the ability to perform lazy loading. Where this sce-nario comes into play most often is when a factory can instantiate a number of subclasses that are defined in separate PHP source files.
Terminology — Lazy Loading
The term lazy loading refers to not performing expensive operations (generally IO operations like includ-ing PHP files or querying a database) before they are absolutely required by the script.
A common technique with web sites is to have multiple web pages dynamically controlled through a single script. Consider blog software that might have different pages for viewing the recent entries, a single entry with comments, a comment submitting page, an archive navigation page, a page for the administrator to edit page, and so forth. You might encapsulate the logic to generate each of these in a class, and use a Factory to load both the class definition and the object. Each of these class-es might be stored in a separate file in a ‘pages’ subdirectory of your application. The code to implement a lazy loading page factory might look like:
|
||
|
|
|||
|
class PageFactory { function &getPage() {
$page = (array_key_exists(‘page’, $_REQUEST)) ? strtolower($_REQUEST[‘page’]) : ‘’; switch ($page) {
case ‘entry’: $pageclass = ‘Detail’; break; case ‘edit’: $pageclass = ‘Edit’; break; case ‘comment’: $pageclass = ‘Comment’; break; default:
$pageclass = ‘Index’; } if (!class_exists($pageclass)) {
require_once ‘pages/’.$pageclass.’.php’; }
return new $pageclass; } }
|
|||
|
|
|||
All Pages All Books