2010-10-01 109 views
1

请问如何在Codeigniter中使用spl_autoload_register()?我需要这样做,因为我使用Codeigniter与另一个也使用自动加载的框架。在Codeigniter中使用PHP spl_autoload_register()

我在这里看到的东西

PHP spl_autoload_register

我不知道如何定位的笨自动加载。我是OOP和Codeigniter的新成员。非常感谢!

上面的链接有这样的:

 

function autoload_services($class_name){ 
    $file = 'services/' . $class_name. '.php'; 
    if (file_exists($file)){ 
     require_once($file); 
    } 
} 

function autoload_vos($class_name){ 
    $file = 'vos/' . $class_name. '.php'; 
    if (file_exists($file)){ 
     require_once($file); 
    } 
} 

function autoload_printers($class_name){ 
    $file = 'printers' . $class_name. '.php'; 
    if (file_exists($file)){ 
     require_once($file); 
    } 
} 

spl_autoload_register('autoload_services'); 
spl_autoload_register('autoload_vos'); 
spl_autoload_register('autoload_printers'); 
+0

你是什么意思“目标CodeIgniter自动加载”?你想构建自己的自动加载器来加载CI类吗?或者你想要在CI自动加载器的旁边加载自己的类(如果有的话,我不知道)? – ircmaxell 2010-10-01 19:06:35

+0

是的,ircmaxwell,我需要使用spl_autoload_register自动加载Codeigniter或其他框架(Flourish)。即如果一个类被调用,如果它没有在Flourish中找到,它将检查CI,反之亦然。目前,我在页面上收到异常错误“无法加载类”。但是,当我禁用任何一个自动加载,它运行良好。它是我需要的组合。你现在明白吗? – Cogicero 2010-10-01 19:56:14

回答

9

感谢http://codeigniter.com/forums/viewthread/73804/#366081和从我在Twitter上关注一些CI民间信息的一些位(我问EM):Eric BarnesDan HorriganPhil SturgeonZack Kitzmiller,我找到了解决办法。如果你是像我这样的CodeIgniter n00b,你可能喜欢关注这些人。

我删除了init.php和config.php,然后将下列内容塞进我的配置文件config.php的底部(我也是从一个名为mylibrary的自定义库中自动加载的)。

function multi_auto_require($class) { 
if(stripos($class, 'CI') === FALSE && stripos($class, 'PEAR') === FALSE) { 
    foreach (array('flourish', 'mylibrary') as $folder){ 
     if (is_file(APPPATH."../auxengines/{$folder}/{$class}.php")){ 
      include_once APPPATH."../auxengines/{$folder}/{$class}.php"; 
     } 
    } 
} 
} 

spl_autoload_register( 'multi_auto_require');

出色地工作。谢谢,人们!

+0

我不得不添加'我'和'MX',因为我使用HMVC扩展,以防万一任何人发现这个答案并不完全解决问题。 – Relequestual 2013-10-30 17:15:41

1

唉唉,我看现在......你所遇到的问题(看a prior question你问之后),因为有2个定义__autoload功能(并因此导致解析错误)......

要定义呼叫spl_autoload_register('yournewfunctionname');后立即修复它,只需重命名其中一个到别的东西,然后......

这应该是所有有给它,只要因为我明白你的意思问题...

+0

感谢您的回复,ircmaxwell。我将蓬勃发展的自动加载函数重命名为___autoload_flourish,并且在定义之后我将其称为spl_autoload_register('___ autoload_flourish');但不,它不工作。我得到了同样的错误。我想我需要了解CI是如何自动加载的,它不是通常的PHP自动加载功能:(你认为怎么样? – Cogicero 2010-10-01 19:52:06

+0

如果无法加载类,它是否会引发异常或发出错误?你发布了这两个函数的代码? – ircmaxell 2010-10-01 19:57:19

+0

我现在工作得很好,谢谢ircmaxwell! – Cogicero 2010-10-04 09:56:21