Reputation: 101906
When building a library I always provide an Autoloader
class that handles autoloading for the library. The autoloader is registered like this:
require_once 'path/to/PHP-Parser/lib/PHPParser/Autoloader.php';
PHPParser_Autoloader::register();
I'm not sure though how to handle it if my library depends on another library. Imagine that PHPParser
depends on a PHPLexer
. Now when using the library one would need to write:
require_once 'path/to/PHP-Lexer/lib/PHPLexer/Autoloader.php';
PHPLexer_Autoloader::register();
require_once 'path/to/PHP-Parser/lib/PHPParser/Autoloader.php';
PHPParser_Autoloader::register();
If there are more than just one dependency or the dependencies have dependencies themselves, this can get messy quickly.
So how should one handle dependency autoloading?
One idea I had was that the library should handle autoloading for it's dependencies too, but that just doesn't feel right. Another idea would be to not provide an autoloader at all and assume that people use the UniversalClassLoader
. That though doesn't seem right either.
Upvotes: 4
Views: 2167
Reputation: 279
add to class constructor
public function __construct(){
$this->Register();
}
after that on page where you whant to make load create an object
$obj = new PHPParser_Autoloader();
Upvotes: -1
Reputation: 165193
Well, there are a few ways to solve this problem, each with their own pros and cons:
Use a common PSR-0 autoloader for all the libraries, and just register the location of the other project when initializing it.
Define a custom autoloader for each library.
Implement a bootstrap.php for each library (preferably provided by the library)
require_once '/path/to/lib/dir/bootstrap.php';
to initializePersonally, I use the third option. An example is the bootstrap.php file in my CryptLib library. To initialize it, just call bootstrap. You could also use any PSR-0 autoloader and just not call bootstrap.php, and it will work just fine. But with the bootstrap option, if I added functionality which needed to register itself at startup, I could just add it to the bootstrap.php file and it would automatically be executed (rather than telling users that they will need to do "x, y, z" on startup)...
With respect to the universal class loader option that you mentioned (calling spl_autoload_register()
with no arguments), I personally don't like that option. First of all, it lowercases the classname (which is in violation of PSR-0, and I don't like it. I have gotten used to case sensitive class -> path mapping, and actually prefer it that way now). Secondly, it always uses relative paths, so it will defeat most opcode caches. There are other issues, but those are the big ones...
Upvotes: 7
Reputation:
If classes in library named by PSR-0 convention, than it's possible to use one autoloader for all libraries. Otherwise, library should provide own autoloader.
Upvotes: 2