views:

176

answers:

1

Hey!

I am creating a small php framework and I have a few classes that use the singleton design pattern. Like for example my Session class uses the singleton pattern because in theory I will only really need one instantiation of the class.

I recently discovered the registry pattern (actually new about it for a while but it sort of came to my mind recently), and so I thought that instead of duplicating code (using php 5.2.12, I still need to create the getInstance method with the class name, only in 5.3 is it possible to create the singleton pattern in a parent class) I could just have a registry class and call my classes with the singleton pattern from there.

Currently in my framework there aren't that many classes implementing the singleton pattern, so the registry class wouldn't have many, but it's still in the early stages so I might find it useful to store some more stuff.

So any ideas or thoughts on this?

+4  A: 

While I do like the Registry pattern, it is my opinion that using Singletons is better than using a Registry in your case of a few globally important unrelated classes. I've read some good articles that disagree with me, but here are my reasons.

Registries seem most useful when you are trying to keep a collection of objects that are related or otherwise not well-known ahead of time. Using a Registry is good especially when all of the returned objects are of the same type. The definition and example of Registry from MartinFowler.com says:

A well-known object that other objects can use to find common objects and services.

You, on the other hand, are trying to store your (small list) of crucial objects, that have different types. (I'm guessing Session, Database, Cache, etc.) It seems to me like you really do want to be sure the type of the object that you're being given, and it's dangerous to do something like:

$registry = Registry::getInstance();
$db = $registry->get("database"); // am I really sure what type $db is?

When you could do this:

$db = Database::getInstance();

The other thing is that you still need global access to the Registry object, so you still either need to make that class a Singleton or you need to pass its instance into every object that needs it -- which is the very thing you were trying to avoid.

I'd love to hear comments from people who disagree though.

philfreo