First of all, the autoload mechanism in PhalApi is very simple. Secondly, PhalApi can work very well with any other autoload mechanism, which means PhalApi do not limit you to only use one way to load file.
In summery, the principle is: simple, uniform, normative.
The relationship between class path and class name in PEAR package is very simple.
And it's much more simpler in PhalApi. We do not consider namespace yet, so let's ignore namespace. Assume we have these classes as below.
Api_User
Domain_User
Model_User
We should have these related class files.
.
|-- Api
| `-- User.php
|-- Domain
| `-- User.php
|-- Model
| `-- User.php
Take another little more complicated class as an example. Class Api_Game_User_Equitment
should be located at file ./Api/Game/User/Equitment.php
.
NOTE: Class name and file path are case-sensitive.
How could we make PhalApi autoload these classes that we just create?
At default, PhalApi do not scan all the folders for performance reasons. It just scan framework and project root folder instead. When there are some new source ocde folders, we need to mount them into PhalApi. That means, we need to tell PhalApi where to find our new project members.
We can finish that easily by using PhalApi_Loader::addDirs().
DI()->loader->addDirs('Demo');
We just add folder Demo
into PhalApi, where our project codes are. If there are serveral folders, we can pass an array instead of a string.
DI()->loader->addDirs(array('Demo', 'Demo1', 'Demo2'));
Please keep in mind that we can only add relative folder paths that inside PhalApi. That is to say, any folders to be added should under path API_ROOT
. On Linux, these three ways are equivalent.
// path: API_ROOT/Demo
DI()->loader->addDirs('Demo');
// path: API_ROOT/./Demo
DI()->loader->addDirs('./Demo');
// path: API_ROOT/Demo
DI()->loader->addDirs('/Demo');
If the folder is not under folder PhalApi, we can solve this problem by using command ls
on Linux.
We can add folder paths but also can add single file path by using PhalApi_Loader::loadFile(). It's different between passing relative file path and absolute file path when load single file.
// path: API_ROOT/Demo/Tool.php
DI()->loader->loadFile('Demo/Tool.php');
// path: /path/to/Demo/Tool.php
DI()->loader->loadFile('/path/to/Demo/Tool.php');