How to autoload Table and Row classes in ZF

This article describes how to use a little hack into the Zend Framework library, for having it autoload an ExampleModel.php file whenever an ExampleTable or ExampleRow class is instantiated.

In my Zend Framework projects I use to split my models into a Table and a Row class, and I put both into the same file, one after the other.

For example, my PersonModel.php holds PersonTable and PersonRow classes. I like to have collection methods like findByFullname into the PersonTable class and instance methods like getGroups into the PersonRow class. And it’s very helpful to have these classes into the same file, due to their coupling.

Zend Framework supports autoloading, and it’s possible to replace the default autoloader with your own, but the autoloading replacement feature is compromised by the use of direct calls to the default loader throughout the library (it occurs 50+ times in ZF 1.6.x).

1. Patch Zend_Loader

Patched Zend_Loader differs from Zend_Loader only for the added lines 7-10. The patch is a contribution of Tomáš Procházka who described it in the issue ZF-2533.

{[ .Zend_Loader | 1.hilite( =php,ln-= ) ]}

2. Add My_Loader

My_Loader differs from Zend_Loader only for the added line 14.

{[ .My_Loader | 1.hilite( =php,ln-= ) ]}

3. Register My_Loader as a replacement for Zend_Loader

Finally, at the beginning of my bootstrap file I register My_loader as the real loader.

{[ .bootstrap | 1.hilite( =php= ) ]}

Final thoughts

The issue ZF-2533 is very old, the proposed patch is simple and effective, still it does not find its way into the trunk. Why?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.