PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 12 ■ ENTERPRISE PATTERNS


return self::$instance;
}


function init() {
$dsn = \woo\base\ApplicationRegistry::getDSN( );
if (! is_null( $dsn ) ) {
return;
}
$this->getOptions();
}


private function getOptions() {
$this->ensure( file_exists( $this->config ),
"Could not find options file" );


$options = SimpleXml_load_file( $this->config );
print get_class( $options );
$dsn = (string)$options->dsn;
$this->ensure( $dsn, "No DSN found" );
\woo\base\ApplicationRegistry::setDSN( $dsn );
// set other values
}


private function ensure( $expr, $message ) {
if (! $expr ) {
throw new \woo\base\AppException( $message );
}
}
}


This class simply reads a configuration file and makes values available to clients. As you can see, it is
another singleton, which is a useful way of making it available to any class in the system. You could
alternatively make it a standard class and ensure that it is passed around to any interested objects. I have
already discussed the trade-offs involved there both earlier in this chapter and in Chapter 9.
The fact that I am using an ApplicationRegistry here suggests a refactoring. It may be worth making
ApplicationHelper itself the registry rather than have two singletons in a system with overlapping
responsibilities. This would involve the refactoring suggested in the previous section (splitting core
ApplicationRegistry functionality from storage and retrieval of domain-specific objects). I will leave
that for you to do!
So the init() method is responsible for loading configuration data. In fact, it checks the
ApplicationRegistry to see if the data is already cached. If the Registry object is already populated,
init() does nothing at all. This is useful for systems that do lots of very expensive initialization.
Complicated setup may be acceptable in a language that separates application initialization from
individual requests. In PHP, you need to minimize initialization.
Caching is very useful for ensuring that complex and time-consuming initialization processes take
place in an initial request only (probably one run by you), with all subsequent requests benefiting from
the results.

Free download pdf