开发者

Proper error handling in a custom Zend_Autoloader?

I'm building a custom autoloader based on Zend Framework's autoloading (related question here).

The basic approach, taken from that question, is

class My_Autoloader implements Zend_Loader_Autoloader_Interface 
{
    public function autoload($class) 
    {
        // add your logic to find the required classes in here
    }
}

and then binding the new autoloader class to a class prefix.

Now what I'm unsure about is how to handle errors inside the autoload method (for example, "class file not found") in a proper, ZF compliant way. I'm new to the framework, its conventions and style.

开发者_开发问答
  • Do I quietly return false and let the class creation process crash?

  • Do I output an error or log message somehow (which would be nice to pinpoint the problem) and return false? If so, what is the Zend way of doing that?

  • Do I trigger an error?

  • Do I throw an exception? If so, what kind?


ZF itself uses two different approaches:

  • Zend_Loader (the old autoloading mechanism) throws a Zend_Exception in case something's wrong
  • Zend_Loader_Autoloader returns false when the used registered autoloader returns false

The Zend_Loader_Autoloader doesn't catch any exception thrown in the used autoloader to eventually your custom exception would bubble up through the Zend_Loader_Autoloader. I personally just return false in case I'm not able to load a requested class.


That depends on the kind of error. I'd consider it a fatal error if a class cannot be loaded. Thus I'd throw an Exception, e.g.

class My_Autoloader_Exception extends Exception {}

You will find that ZF uses a lot of custom Exceptions on the package level and also provides a class for this to extend from (though I'd consider this optional).

Incidentally, there is a usage example of Zend_Exception with their autoloader:

  try {
      // Calling Zend_Loader::loadClass() with a non-existant class will cause
      // an exception to be thrown in Zend_Loader:
      Zend_Loader::loadClass('nonexistantclass');
  } catch (Zend_Exception $e) {
      echo "Caught exception: " . get_class($e) . "\n";
      echo "Message: " . $e->getMessage() . "\n";
      // Other code to recover from the error
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜