What about using a Factory? It seems that would be most appropriate for initializing the objects. Or am I way off? This is my first dive into the deep waters of Design Patterns
A few things to keep in mind. A key goal often found in a design pattern implementation is to reduce dependency. In your initial example, your Application class has three dependencies and growing. It really seems like you are finding your way towards a
Registry. A Registry put in simplest terms is a basket - you can store objects in it and grab one when required.
In your original post I would have a
Registry object (follow the link for the code) and in one of my bootstrap files
Code: Select all
$error = new Error();
$page = new Page();
$mysql = new MySQL_Class();
$registry = new My_Registry;
$registry->register('error', $error);
$registry->register('page', $page);
$registry->register('mysql', $mysql);
// or condense the above into the form
$registry = new My_Registry;
$registry->register('error', new Error);
// etc.
A Registry is a basic idea - don't take the example implementation as the end of the line. Zend Framework implements a Registry as static methods on the base Zend class, for example. It boils down to the same functionality, just with a varying interface. I believe that's been refactored into a dedicated Zend_Registry soon...
A
Factory Pattern differs since it does not replace a Registry. Both are independent Patterns with separate uses. Where a Registry stores objects (or any value by the way) in a single parcel (easy to pass as parameter, or as a Singleton, or with static methods), a Factory is useful when creating an object requires a series of steps beyond a simple new Class(); statement. A fair example is where the decision on which one of a varying family of classes with identical API's requires some logic. For example, deciding whether to use Mysql_Class, Mysqli_Class, Postgres_Class, Sybase_Class, etc. It's usually a single Factory method on another class, or can be a standalone class itself. It's usually only useful where decision or initialisation logic exists which would be duplicated across the application unless centralised in a Factory. It's usually good practice to avoid Factories unless you're certain it's needed.
As an example, you could use a Factory to determine which Database class to initialise, and register the resulting object to a Registry. Both being used in concert...

.