(Yaf >=1.0.0)
Yaf_Loader 為 Yaf 引入了一個全面的自動載入解決方案。
第一次取得 Yaf_Application 的實例時,Yaf_Loader 會實例化一個單例,並將自身註冊到 spl_autoload。您可以使用 Yaf_Loader::getInstance() 取得實例。
Yaf_Loader 只會嘗試載入類別一次,如果失敗,則取決於 yaf.use_spl_auload 的設定。如果此設定為開啟,Yaf_Loader::autoload() 將會回傳 false
,讓其他自動載入函式有機會執行。如果此設定為關閉(預設值),Yaf_Loader::autoload() 將會回傳 true
,更重要的是,會觸發一個非常有用的警告(對於找出為何無法載入類別非常有幫助)。
注意事項:
除非某些函式庫有自己的自動載入機制且無法改寫,否則請保持 yaf.use_spl_autoload 設定為關閉。
預設情況下,Yaf_Loader 假設所有函式庫(類別定義的程式碼)都儲存在 全域函式庫目錄 中,該目錄定義在 php.ini(yaf.library) 中。
如果您希望 Yaf_Loader 在 區域類別目錄(定義在 application.ini 中,預設為 application.directory . "/library")中搜尋某些類別(函式庫),您應該使用 Yaf_Loader::registerLocalNameSpace() 註冊類別前綴。
讓我們來看一些例子(假設 APPLICATION_PATH 為 application.directory)
範例 #1 設定範例
// Assuming the following configure in php.ini: yaf.library = "/global_dir" //Assuming the following configure in application.ini application.library = APPLICATION_PATH "/library"
範例 #2 註冊區域命名空間
<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
public function _initLoader($dispatcher) {
Yaf_Loader::getInstance()->registerLocalNameSpace(array("Foo", "Bar"));
}
?>
範例 #3 載入類別範例
class Foo_Bar_Test => // APPLICATION_PATH/library/Foo/Bar/Test.php class GLO_Name => // /global_dir/Glo/Name.php class BarNon_Test // /global_dir/Barnon/Test.php
範例 #4 載入命名空間類別範例
class \Foo\Bar\Dummy => // APPLICATION_PATH/library/Foo/Bar/Dummy.php class \FooBar\Bar\Dummy => // /global_dir/FooBar/Bar/Dummy.php
您可能會注意到所有資料夾的首字母都大寫,您可以透過在 php.ini 中設定 yaf.lowcase_path = On 將它們改為小寫。
Yaf_Loader 也設計用於載入 MVC 類別,規則如下:
範例 #5 MVC 類別載入範例
Controller Classes => // APPLICATION_PATH/controllers/ Model Classes => // APPLICATION_PATH/models/ Plugin Classes => // APPLICATION_PATH/plugins/
範例 #6 MVC 類別區分
Controller Classes => // ***Controller Model Classes => // ***Model Plugin Classes => // ***Plugin
範例 #7 MVC 載入範例
class IndexController // APPLICATION_PATH/controllers/Index.php class DataModel => // APPLICATION_PATH/models/Data.php class DummyPlugin => // APPLICATION_PATH/plugins/Dummy.php class A_B_TestModel => // APPLICATION_PATH/models/A/B/Test.php
此外,目錄會受到 yaf.lowcase_path 的影響。注意事項:
從 2.1.18 版本開始,Yaf 支援使用者程式碼端的控制器自動載入(這表示由使用者 PHP 程式碼觸發的自動載入,例如:在 Bootstrap 或 Plugins 中存取控制器的靜態屬性),但自動載入器只會嘗試在預設模組資料夾 "APPLICATION_PATH/controllers/" 下找到控制器類別程式碼。
預設情況下,此值為 application.directory . "/library",您可以在 application.ini(application.library) 中更改此值,或呼叫 Yaf_Loader::setLibraryPath() 進行更改。