Search code examples
phpzend-frameworkmoduleclassloaderzend-autoloader

Module autoloader in Zend framework


I developing a project using Zend framework and I came across the following problem. I'm using Zend framework MVC folder structure generated using their zf.sh script.

My library folder has the Zend library folder and it's classes can be called normally inside the application. I created another folder inside my library for my classes. This is the folder structure now:

MyProject

|_application
|_docs
|_public
|_library
           |_Zend
           |_Buyers
                     |_Donations.php
|_scripts

I named my Donation class "Buyers_Donations" as the Zend framework naming convention.

When I tried using this class inside my controller

$obj= new Buyers_Donation(); 

it gave an error can not find class Buyers_Donation inside the controller.

But when I added the following line in my Bootstrap it worked:

$loader = Zend_Loader_Autoloader::getInstance();
$loader->setFallbackAutoloader(true);
$moduleLoder = new Zend_Application_Module_Autoloader(
array(
'namespace'=>'',
'basePath'=>dirname(__FILE__)
));

Could someone please explain what actually happened and what is the use of the module autoloader although I don't have any modules in my application ?


Solution

  • As you suspected, you shouldn't be using the module autoloader since you're not using modules. Assuming the Zend* classes are autoloading correctly for you, all you need to do is tell the standard autoloader that it should also be used for classes in your 'Buyers' namespace. So instead of the code snippet you posted, just do:

    $loader = Zend_Loader_Autoloader::getInstance();
    $loader->registerNamespace('Buyers_');
    

    you can also set this in application.ini if you prefer.

    I'm also assuming that your classes are in the library folder, and not in the public directory as your question implies (this would be bad).