Thursday, March 31, 2011

Zend Framework Autoloading - Finding Your Library Classes

Attention Zend Framework beginners.  Since today is the final day for me to get around to contributing - in some small way - to The Ideas of March, which encourages people to blog more often, I offer up the following.

If you find yourself using require_once statements in your Zend Framework applications in order for ZF to find your library classes, in spite of using Zend_Application - which you know establishes autoloading by default - then there is one simple thing you need to add to your application's config file, typically configs/application.ini, to fix the problem.  End your frustration, and read on.

Assuming a directory structure something like this (my "vendor prefix" of EAI stands for Everetts Associates, Inc.):
application/
data/
docs/
library/
        EAI/
            Mail.php
public/
scripts/
temp/
tests/

and a class named EAI_Mail in the Mail.php file, and assuming your library is on your include_path, all that is needed is a line like this in application.ini:

autoloaderNamespaces[] = "EAI_"

Zend Framework's autoloader is already configured to match class prefixes Zend_ and ZendX_.  What you're doing by adding the above line to the application's config file is register your library prefix/namespace with the autoloader.  The include_path was not your problem, the problem was that ZF wasn't acknowledging your class prefix.

Now you can strip out those require_once statements for a bit of a performance boost.

Happy coding.

No comments:

Post a Comment