我的基本方法是创建一个带有观察者的自定义模块
controller_front_init_before
事件。在事件观察器中,您可以根据需要设置自动加载器。有一篇 Magento Wiki 文章设置事件观察者. The controller_front_init_before
event 是 Magento 中第一个触发的非通用事件之一。这就是我们使用它的原因。
我们需要解决的大问题是:Magento 的自动加载器首先在堆栈上,如果它找不到文件(EZComponent 类就是这种情况),它的包含将引发一个错误,从而停止执行。
所以,我们在上面的事件观察器中需要做的是
去除Varien_Autoloader
来自spl_autoload stack
注册我们自己的自动加载器(我们将使用Zend_Autoloader
,因为它随 Magento 一起提供,而且您似乎很熟悉它)
重新添加Varien_Autoloader
到堆栈
自从加载了类中的类后,我们需要做一些额外的调整Zend
命名空间通常由我们将删除的自动加载器处理。查看评论了解更多详情
//we need to manually include Zend_Loader, or else our zend autoloader
//will try to use it, won't find it, and then try to use Zend_Loader to
//load Zend_Loader
require_once('lib/Zend/Loader.php');
//instantiate a zend autoloader first, since we
//won't be able to do it in an unautoloader universe
$autoLoader = Zend_Loader_Autoloader::getInstance();
//get a list of call the registered autoloader callbacks
//and pull out the Varien_Autoload. It's unlikely there
//are others, but famous last words and all that
$autoloader_callbacks = spl_autoload_functions();
$original_autoload=null;
foreach($autoloader_callbacks as $callback)
{
if(is_array($callback) && $callback[0] instanceof Varien_Autoload)
{
$original_autoload = $callback;
}
}
//remove the Varien_Autoloader from the stack
spl_autoload_unregister($original_autoload);
//register our autoloader, which gets on the stack first
require_once('library/EZComponents/Base/src/base.php');
$autoLoader->pushAutoloader(array('ezcBase', 'autoload'), 'ezc');
//lets just make sure we can instantiate an EZ class
#$test = new ezcBaseFile();
#var_dump(get_class($test));
//IMPORANT: add the Varien_Autoloader back to the stack
spl_autoload_register($original_autoload);
将上面的代码放入观察者方法中,您应该可以开始了。
您可以采取的另一种方法(更适合 Magento 模式)是创建一个实现 EZComponent 加载程序的自定义模块。
$o = Mypackage_Mymodule_Loader::getModel('ezcBaseFile');
然后,您可以在静态 getModel 方法中实现自动加载器风格的 require 代码,并在需要 ezcBaseFile 类时使用它。如果您想在某个对象上调用静态方法,您可能需要在不实例化对象的情况下加载类的方法。ezcBaseFile
基类。
$o = Mypackage_Mymodule_Loader::getLoadclass('ezcBaseFile');