After much deliberation and discussions with friends (thanks Mark), I have decided to embrace PHP5's built in __autoload function. I have chosen a method briefly documented on phpKitchen. For those of you who do not know what PHP5 __autoload is, no worry go here for a review
The short of it is for a class in the path {base class path}/persist/database/DbAdapter.php the class in the file dbAdapter.php would be named persist_database_DbAdapter. You then define an __autoload function similar to this...
So now what does this get us?? Instead of something like this...
can simply do...
$dbAdapter = persist_database_DbAdapter::getInstance();
Then when PHP tries to load the unknown class, persist_database_DbAdapter, the __autoload function will be called which will build the appropriate require_once statement to locate the class.
Now some may see this as casting the slight complexity of all those require_once statements only to add complexity of having strange class names like persist_database_DbAdapter. I may agree with this point of view but I would argue that there are much greater benefits to using __autoload() than just getting rid of those require_once statements and I will briefly summarize two of them below.
The first advantage (lesser of the two), is one of code readability. Whereas above I described the class name of persist_database_DbAdapter as ”strange”, I would suggest that the long class name actually helps to describe the true purpose of the class, making the code more readable by just the nature of the class name. Thus reducing the need to clutter the code with /* comments */.
The second advantage is much more substantial one and it involves what is often referred to as Lazy Initialization. What I often see happening in PHP is that required files for a Class are often added at the top of the file (outside of any methods). With this setup, whenever the Class is referenced all these requires are parsed and included regardless of if all the files they are including will actually be used on the particular Request cycle. Depending on the size of some of the files being parsed, this can be quite an expensive operation. For example, with the code below...
If getBar() is never called for this particular use of the class Bar, the process time of require_once(CLASS_PATH.'/foo/Bar.php') has been waisted. On the other hand if we use __autoload() the above code becomes simply...
So, in this case the require_once(CLASS_PATH.'/foo/Bar.php'); only occurs the instant before it is actually required (and never if it is not required). This is essentially the performance enhancement Pattern know as Lazy Initialization and when you are dealing with large and/or numerous class files, the processor time savings can be quite substantial.

0 comments:
Post a Comment