I’m developing a framework that uses similar naming conventions that of the Zend Framework in that the namespace + class name maps to the file path. Example: Framework\Database\Mysql maps to Framework/Database/Mysql.php (it’s not literally called “Framework”. Just an example).
When one class explicitly depends on another I use something like:
require_once 'Framework/Path/To/File.php';
I rely on the include path being set to the directory just above Framework/ and avoid concatenating the path (using a constant string is more efficient).
In Loader.php I have this just above “class Loader” for classes that need the project path (for default locations, like cache path, or the optional SPL autoload):
The reason for it being conditional is that DIR resolves symlinks, so the user may need to set it themselves if Framework/ is a symlink. This constant is used in some classes configuration defaults (cache directory), or the optional SPL autoload (is_file doesn’t resolve include path).
Now the question is:
Should I set the include path in the framework, or should I rely on the user to do it in their code? When the include path needs to be set, what is the “best practice”?
If the user is the one that should set it, they should set it to Framework\PATH. But I could just do it just after Framework\PATH’s define.
I’m thinking it would be better for the user to do it because if they need to add their own include path they can do it all in one call.
And more portable. I find that quite a lot more important.
What do you need Framework\PATH for? if include_path is set properly, even your autoloader will just include and it’ll work.
I would say that best practice is to leave it to the user. Additionally, letting the user set the autoloader is also a good idea, as they might want to get multiple libraries/frameworks to function together. You could ship your code with a default bootstrap file where this stuff is set up. Most users will then just use this, but they could optionally provide their own.
I use spl_autoload_register for the autoloader with my own function that uses is_file and require_once. The reason is I don’t use spl_autoload is because it lower-cases file names, which causes things not to work on case sensitive file systems.
Unfortunately is_file nor file_exists is include path aware, so I need an absolute path for it to work. I could see what require_once returns, but it also throws a warning. If I suppress it with @ parse errors also get suppressed.
I also prefer to have a class isn’t defined error verses file cannot be found.
I will let the user set it up the include path. I have Loader::registerAutoloader() to set up the auto loader (it’s optional).
Thank you for your feedback. Really appreciate it. Any other advice is welcome as well. Thanks :).