Magic Factory Method for Obtaining Instances of Zend_Gdata Classes

by Hui Wang

// Create a new entry using the calendar service's
//magic factory method
$service = new  Zend_Gdata_Calendar($client);
$event= $service->newEventEntry();

This is a small piece of code from Zend manul on how to use Google Calendar.

At first I didn’t notice the comment in the very first line.  I have navigated directly into the class Zend_Gdata_Calendar to explore the method newEvenEntry. Unfornately and weirdly, this method doesn’t exist !

My first reaction was that this method may be defined in some other classes. So I made a global search in Eclipse PDT for this method. Always no luck.

Then I thought maybe the search functionality in PDT doesn’t work well because I can’t image how a method could be called if it is not defined. I turned to Zend_Gdata documentation to make another check. In fact, the search functionality provided by PDT always works well. So I’ve got the same result : There is no definition for this method.

At last, I decided to read again the code. With few efforts, I find the magic thing that I’ve never met before. The magic factory method ! A quick Google search unveiled its mystery.

The Zend Framework naming standards require that all classes be named based upon the directory structure in which they are located. For instance, extensions related to Spreadsheets are stored in: Zend/Gdata/Spreadsheets/Extension/... and, as a result of this, are named Zend_Gdata_Spreadsheets_Extension_.... This causes a lot of typing if you’re trying to construct a new instance of a spreadsheet cell element!

We’ve implemented a magic factory method in all service classes (such as Zend_Gdata_App, Zend_Gdata, Zend_Gdata_Spreadsheets) that should make constructing new instances of data model, query and other classes much easier. This magic factory is implemented by using the magic __call method to intercept all attempts to call $service->newXXX(arg1, arg2, ...). Based off the value of XXX, a search is performed in all registered ‘packages’ for the desired class.  [source]

Conclude

When we think that we’ve understood the code, we may not. Don’t ignore the comments. They exist because they have to.