如何使用单个实例在自动加载中注册路径. [英] How to register path in autoload using a single instance.
问题描述
很抱歉,标题含糊不清,但我试图找到一些更好的替代方法,以不必多次调用Autoloader
类和register
方法来映射类路径,如下所示.
Sorry about the vague title, but I am trying to find some better alternatives to having to call an Autoloader
class, and the register
method multiple times, to map class paths as seen below.
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/someclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(_DIR__.'/path/to/anotherclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/anotherclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/anotherclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/anotherclass');
$ClassLoader->register();
这持续约50行,我想知道如何用简单的几行解决方案来处理自动加载类.我显然可以向构造函数注入数组:
This goes on and on for about 50 lines, and I would like to know how I can handle the autoloading classes with simple few lines solution. I can obviously inject an array, to the constructor:
$ClassLoader = new Autoloader\Loader( ['paths'=>[
'/path/to/class/',
'/path/to/anotherclass',
'/path/to/anotherclass'
]);
$ClassLoader->register();
但是,我不确定从OOP良好实践的角度来看是否建议至少使用此方法.
But, I am not sure if this method is recommended at-least from OOP good practice point of view.
推荐答案
也许这就是您想要的.
对于包含类的每个目录,运行::add
.
Perhaps this is what you are looking for.
For each directory that contains your classes run ::add
.
namespace ClassLoader;
class Loader
{
protected $directories = array();
public function __construct()
{
spl_autoload_register([$this, 'load']);
}
public function add($dir)
{
$this->directories[] = rtrim($dir, '/\\');
}
private function load($class)
{
$classPath = sprintf('%s.php', str_replace('\\', '/', $class));
foreach($this->directories as $dir) {
$includePath = sprintf('%s/%s', $dir, $classPath);
if(file_exists($includePath)) {
require_once $includePath;
break;
}
}
}
}
$loader = new Loader();
$loader->add(__DIR__.'/src');
$loader->add(__DIR__.'/vendor');
use Symfony\Component\Finder\Finder;
$finder = new Finder();
// Included /var/www/test/vendor/Symfony/Component/Finder/Finder.php
// I put the Symfony components in that directory manually for this example.
print_r($finder);
它实际上与作曲家相同,只是适应性或性能较低.
It is effectively the same as with composer though, just less adaptive or performant.
这篇关于如何使用单个实例在自动加载中注册路径.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!