Question

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.

Was it helpful?

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.

OTHER TIPS

if you name your class according to zend conventions, the class should autoload without problem. If your class is located at /application/models/myClass.php and is named :

class Application_Model_MyClass {

    public function myMethod(){
    }
}

it should autoload just fine, I don't think the fact that is a singleton would affect autoloading.

If you need to use your own class names you can add a new namespace to the autoloader the works in the /library directory, add this line to your application.ini :

autoloaderNamespaces[] = "MyNamespace_"

then add the /MyNamespace directory to the /library directory and name your files accordingly:

class MyNamespace_MyClass {
}

Hope this helps.

If class names and locations in your library do not follow Zend naming conventions, then you can write an autoloader for that library and push this autoloader onto the Zend_Loader_Autoloader stack.

See https://stackoverflow.com/a/8820536/131824 for an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top