2014-03-07 63 views
4

我已經在Phil's Sturgeon example之後創建了兩個控制器,Public_Controller和Admin_Controller在./application/libraries文件夾中。CodeIgniter自動加載特定類

我想要做的是自動加載Public_Controller和Admin_Controller specificly,所以我創建./application/config.php

function __autoload($class) { 

    // Autoload only Public_Controller and Admin_Controller 
    if (strpos($class, 'CI_') !== 0) { 
     $file = APPPATH . 'libraries/'. $class .'.php'; 
     if (file_exists($file) && is_file($file)) { 
      @include_once($file); 
     } 
    } 
} 

這個我認爲這個問題在這裏面自動加載功能,我有更多的包含在庫文件夾內的文件,所以這些文件也是自動加載的,這不是我想要的。所以不是我試圖做一個小改動,第一個if語句,就像這樣:

if (in_array($class, array('Public_Controller, Admin_Controller'))) // instead of strpos 
爲了目標只有這兩個類

,但這似乎並沒有工作。任何想法我可能做錯了什麼?

回答

0

我只在前端要自動加載Public_Controller和管理Admin_Controller,所以autoload.php超出。在autoload.php文件全局加載。 __autoload()函數只會在被調用時嘗試自動加載類,但未找到。

+0

然後你可以這樣做:'$ this-> load-> model('Model_name');'在你想要的控制器裏面。 – Albzi

0

沒有必要寫自動加載功能 笨已經爲AUO加載文件,如庫和輔助它自己的文件

您可以在特定的陣列

在裏面添加類名的文件名應該是「 autoload.php「在應用程序/配置/目錄

4

轉到applications/config/autoload.php並在那裏你可以編輯你所需要的。

他們是在陣列和packageslibrarieshelpersconfiglanguagesmodels分隔。

$autoload['libraries'] = array('database', 'session'); 

$autoload['helper'] = array('url', 'html', 'form'); 
-1

ü不需要寫..codeiniter具有自動加載特定文件的ibuilt dunction自動加載功能...

去應用/配置/ autoload.php療法U可以將您的特定文件添加到陣列中

$autoload['libraries'] = array('database', 'session','your-specific_file'); 
+0

$ autoload ['libraries'] = array('database','session','folder/your-specific_file');我們可以這樣做嗎? – Angel

+0

autoload假定您已將自定義庫放置在由Codeigniter提供的庫文件夾中。 – Mohan

+0

是我的代碼吧? – Angel

-1

您可以使用您的方法。 __autoload() will NOT自動加載其他類。因爲根據PHP文檔,

__autoload() - 嘗試加載undefined類。當你調用(init)它們時,你的類文件將被「自動」包含在它們中,但不包含這些函數:「include,include_once,require,require_once」。

所以不需要擔心其他類會自動。

OR

可以使用CodeIgniter的內置自動加載功能爲

打開應用程序/配置/自動加載。PHP文件並添加您想要加載到自動載入數組的項目。您會在對應於每種類型的項目的 文件中找到說明。 - 笨文檔

希望這有助於:)

+0

如果Downvoter可以解釋爲什麼這個投票被拒絕,那麼他人也會更清楚! – IJas