Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

namespaces - PHPExcel class not found in Zend Autoloader

I am struggling with namespaces in Zend Framework (at least I think it's a namespace issue).

I want to integrate PHPExcel into my Zend project. Relevant file structure is as follows:

/
 -library
   -ABCD
   -PHPExcel
   -Zend
   -ZendX
   -PHPExcel.php

Custom classes work fine, after

Zend_Loader_Autoloader::getInstance()->registerNamespace('ABCD_');

in the bootstrap. Also, those classes are all named ABCD_blahdeblah.

However, doing registerNamespace('PHPExcel_') doesn't help Zend find the appropriate classes. When I try

$sheet = new PHPExcel; 

in the controller, I get a "Class not found" error. I am guessing that this is either because classes in PHPExcel aren't named with the namespace prefix, or because the main PHPExcel.php file sits outside of the namespace I've just declared. But the PHPExcel structure demands that it sit in the parent directory of the rest of the class/font/etc files.

Any pointers would be greatly appreciated.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create an autoloader for PHPExcel and add it to the Zend autoloader stack.

In library/My/Loader/Autoloader/PHPExcel.php:

class My_Loader_Autoloader_PHPExcel implements Zend_Loader_Autoloader_Interface
{
    public function autoload($class)
    {
        if ('PHPExcel' != $class){
            return false;
        }
        require_once 'PHPExcel.php';
        return $class;
    }
}

And in application/configs/application.ini:

autoloadernamespaces[] = "My_"

Then, in application/Bootstrap.php:

protected function _initAutoloading()
{
    $autoloader = Zend_Loader_Autoloader::getInstance();
    $autoloader->pushAutoloader(new My_Loader_Autoloader_PHPExcel());
}

Then you should be able to instantiate PHPExcel - say, in a controller - with a simple:

$excel = new PHPExcel();

The only sticky part is all of this is how PHPExcel handles loading all its dependencies within its own folder. If that is done intelligently - either with calls like require_once basename(__FILE__) . '/someFile.php' or with its own autoloader that somehow doesn't get in the way of the Zend autoloader - then all should be cool. #famouslastwords


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...