LampCMS development and php tips

Announcements and articles about this site development and stuff like that

Why use factory() over __construct()
Wed Dec 9 2009
Because when instantiating object with new object()
the return value is always an object of class you calling.

The factory() lets you instantiate an arbitraty class based on some conditions. For example if you want to instantiate an object that handles image processing you can have a factory() method check if magicwand is available on the server and instantiate a magickwand-based class OR in magick wand not available it will instantiate a GD based class. These objects will be of the same class - one may extend the other OR they may implement the same interface.
This means you don't care which type of object is returned since both will have the same methods and method signatures. You just get the one that works best and can just use it.

Another important possibility is that factory() may also return something other than an object.
For example a NULL

Sometimes instantiating an object does not make sense. For example, you may ask for an object of type ArrayObject, so you ask the database layer to return array of values based on some sql query, but if query does not return any values (like user with the email address does not exist), then instead of getting ArrayObject with an empty array, you would preffer getting NULL or FALSE back.

First of all it will same a bit of time because you don't instantiate any object and second, your application will be able to examine the returned value and if its === null then you take appropriate actions.

For example, you want to find array or user data based on email address. You execute a mysql query and if record is found you return ArrayObject with underlying array returned by database. For example array like firstName=>'bob', lastName=>'Smith'

The application that asks for this object will get back the object and add it to cache (so that next time it will get the object from cache)

But if database returned an empty result, instead of returning an ArrayObject with empty array, you get back the NULL, so your program will NOT put the NULL in cache because it just does not make sence to cache NULL