Search code examples
zend-frameworkzend-autoloader

How to autoload a singleton class (private constructor) in zend controller?


I have a singleton class in my models directory and I have to use its function in Controller class. Doing it by require_once('file path'); and calling function as ClassName::FunctionName() works fine, but I need to use Zend Autoloader instead of including class through require_once. I came across number of solutions here on stackoverflow which used bootstrap.php in terms of adding following code there and it seems like doing the same as require_once('file path'); did in controller

  protected function _initAutoload()
    {   
       Zend_Loader_Autoloader::getInstance();
    }

Going this way I get Fatal error: Class 'ClassName' not found in {path}\controllers\SampleController.php on {line no.} I am sure I am missing something but cant figure out what exactly.


Solution

  • Like user1145086 has rightly said, if you follow the naming convention of Zend, you class should be auto-loaded.

    If you have a class, say AutoloadedClass, and you want it auto-loaded, you can do the following:

    1. Create a folder in your /library folder and name it 'My'.
    2. Write the following code in your Bootstrap's initAutoload class method:

      Zend_Loader_Autoloader::getInstance()->registerNamespace(array('My_'));
      
    3. Place the file containing the 'AutoloadedClass' in the 'My' folder you just created and rename the file to AutoloadedClass.php so the file is eventually located thus: /library/My/AutoloadedClass.php
    4. Lastly, rename the class itself to My_AutoloadedClass as Zend's naming convention requires. You can henceforth get a reference to your class using that class name My_AutoloadedClass from anywhere in your application.