在构建库时,我总是提供一个处理库自动加载的Autoloader类。自动加载器是这样注册的:
require_once 'path/to/PHP-Parser/lib/PHPParser/Autoloader.php';
PHPParser_Autoloader::register();不过,如果我的库依赖于另一个库,我不知道如何处理它。假设PHPParser依赖于PHPLexer。现在,在使用库时,需要编写:
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();如果有不止一个依赖项,或者依赖项本身也有依赖项,那么这种依赖关系很快就会变得一团糟。
因此,如何处理依赖关系自动加载?
我的一个想法是,库也应该处理自动加载,因为它的依赖性,但这只是觉得不对。另一个想法是根本不提供自动加载器,并假设人们使用UniversalClassLoader。但这似乎也不对。
发布于 2011-09-09 18:14:13
嗯,解决这个问题有几种方法,每种方法各有优缺点:
- Advantages:
1. Very simple to implement
2. Uses same code, so only one autoloader to use
3. You can register all the paths in your application bootstrap file, so all library autoloading is defined in one place
- Disadvantages
1. Requires all libraries to implement a PSR-0 compatible file structure
2. Leaks the abstraction level a bit since the application bootstrap needs to bootstrap everything inside the application including each individual library.
3. Tightly couples the library's file structure to your autoloader (if a library implements a new file that conflicts, it'll break your autoloader even though theirs works file)
- Advantages
1. Very simple to implement.
2. Keeps library autoloading semantics in the library.
3. Better maintainable code due to separation of responsibility
- Disadvantages
1. Lots of hard-coded classes in your bootstrap file (not a big deal though)
2. Performance since an autoloaded class must go through multiple autoloaders
3. Leaks the abstraction level since a library may need more effort to bootstrap than just an autoload
- Advantages
1. Pretty simple to implement.
2. Keeps library autoloading semantics in the library
3. Better code due to separation of concerns
4. Ability to define non-trivial library bootstrap code without clouding other parts of the application
- Disadvantages
1. Still require a `require_once '/path/to/lib/dir/bootstrap.php';` to initialize
2. Performance (for the same reason as the 2nd solution)
3. Most 3pd libraries do not implement a bootstrap file, so you may have to maintain one.
就我个人而言,我使用第三种选择。一个例子是我的bootstrap.php文件库中的CryptLib。要初始化它,只需调用引导程序即可。您也可以使用任何PSR-0自动加载程序,只需不调用bootstrap.php,它就可以正常工作。但是使用引导选项,如果我在启动时添加了需要注册自己的功能,我只需将其添加到bootstrap.php文件中,它就会自动执行(而不是告诉用户他们需要在启动时执行"x,y,z“).
关于您提到的通用类加载器选项(调用没有参数的spl_autoload_register() ),我个人不喜欢这个选项。首先,它降低了类名(这违反了PSR-0,我不喜欢它)。我已经习惯了区分大小写的类->路径映射,现在我更喜欢这种方式)。其次,它总是使用相对路径,因此它将击败大多数操作码缓存。还有其他问题,但这些都是大问题.
发布于 2011-09-09 14:34:11
如果库中的类由PSR-0约定命名,则可以为所有库使用一个自动加载程序。否则,图书馆应提供自己的自动加载器。
发布于 2011-09-09 14:24:50
添加到类构造函数中
public function __construct(){
$this->Register();
}之后,在要加载的页面上创建一个对象
$obj = new PHPParser_Autoloader();https://stackoverflow.com/questions/7362957
复制相似问题