2
Vote

Yii Framework Autoloader compatibility fix

description

It can be somewhat troubling to get started with using this extension in the Yii framework, because the Yii autoloader throws exceptions when it cannot find a class files, preventing other autloaders to do their work.

Since PHPExcel's class names are not compatible with the Yii autoloader, and the Yii autoloader takes precedence over PHPExcel's autoloader you cannot get PHPExcel to work in the framework without either spl_unregistering the Yii autoloader before use and re-registering it after use, but this workaround can easily be prevented by implementing a fix in PHPExcel's autoloader.

For example you could add a beforeAutoloadRegister() and an afterAutoloadRegister to swap around the order in which these autoloaders work, saving you the trouble of having to repeat this manually (and figuring it out when using this library for the first time).

Thanks to softark and Antonio Ramirez for pointing me in the right direction getting this to work.
/**
 * PHPExcel_Autoloader
 *
 * @category    PHPExcel
 * @package     PHPExcel
 * @copyright   Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
class PHPExcel_Autoloader
{
    /**
     * Register the Autoloader with SPL
     *
     */
    public static function Register() {
        if (function_exists('__autoload')) {
            //  Register any existing autoloader function with SPL, so we don't get any clashes
            spl_autoload_register('__autoload');
        }
        $registered = false;
        if(self::beforeAutoloadRegister()) {
            //  Register ourselves with SPL
            $registered = spl_autoload_register(array('PHPExcel_Autoloader', 'Load'));
            self::afterAutoloadRegister();
        }
        
        return $registered;
    }   //  function Register()

    private static function beforeAutoloadRegister()
    {
        //fix for usage in Yii framework v1.1.x (unregister Yii's autoloader)
        if(class_exists('YiiBase') && method_exists('YiiBase','autoload'))
            spl_autoload_unregister(array('YiiBase', 'autoload'));
        
        return true;
    }
    private static function afterAutoloadRegister()
    {
        //fix for usage in Yii framework v1.1.x (re-register Yii's autoloader)
        if(class_exists('YiiBase') && method_exists('YiiBase','autoload'))
            spl_autoload_register(array('YiiBase', 'autoload'));
    }

comments