A little while, I had to build a .xls export function into a Yii application. I decided to use PHPExcel for this, since I had used it before. It's also probably the best Excel importer/exporter for PHP. I soon figured that this didn't go as smooth as I expected.
The problem
Yii kept throwing an Exception about it not being able to find the file to import. Of course it couldn't find the file because PHPExcel's importer was supposed to handle that. I searched around and found a couple of posts like this one. This failed for me because between the spl_autoload_unregister and spl_autoload_register calls, I had to get info from a Model through another Model. When you try to reach a related Model, Yii actually tries to autoload that Model. But since we just unregistered the yii autoloader by calling spl_autoload_unregister, the Yii import was never called and so autoloading the Model failed.
The solution
So I went on and figured out that the reason they unregistered the Yii autoloader, was because the Yii autoloader was called before the PHPExcel autoloader. Since the Yii autoloader throws an Exception when it can't find a file and PHPExcel doesn't, the solution was simple: switch the order in which the autoloaders get registered. I decided to do this by changing the PHPExcel Autoloader's register method from this:
<?php
public static function Register() {
return spl_autoload_register(array('PHPExcel_Autoloader', 'Load'));
} // function Register()
To this:
<?php
public static function Register() {
$functions = spl_autoload_functions();
foreach($functions as $function)
spl_autoload_unregister($function);
$functions=array_merge(array(array('PHPExcel_Autoloader', 'Load')), $functions);
foreach($functions as $function)
$x = spl_autoload_register($function);
return $x;
} // function Register()
So this is what happens:
- All registered autoload functions are saved in $functions.
- Then they all are unregistered.
- Next we put PHPExcel_Autoloader in front of array we named $functions.
- We register all of them in that same order.
- And we return the $functions array
The thing with this is, you can use this everywhere. So if you change the PHPExcel autoloader and you decide to use it later in a project which is not built with Yii, it'll still work fine! From now on PHPExcel's AutoLoader will never be a problem again, no matter which framework you use!
All I have to do now is create a patch and submit it to http://phpexcel.codeplex.com/ so no one will ever have that problem again. Or maybe I should just wait till I have at least 100 comments before I do that 
Click the link below to download the fixed Autoloader.php for PHPExcel 1.7.3c
Autoloader for PHPExcel 1.7.3c Autoloader.php (1.84 kb)
Autoloader for PHPExcel 1.7.6 Autoloader.php (2.15 kb)