如何使用单个实例在自动加载中注册路径


How to register path in autoload using a single instance.

很抱歉标题不明确,但我正在努力寻找一些更好的替代方案,以避免必须多次调用Autoloader类和register方法来映射类路径,如下所示。

$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行,我想知道如何用简单的几行解决方案处理自动加载类。很明显,我可以向构造函数注入一个数组:

 $ClassLoader = new Autoloader'Loader( ['paths'=>[
                     '/path/to/class/', 
                     '/path/to/anotherclass',
                     '/path/to/anotherclass'
 ]);
 $ClassLoader->register();

但是,至少从OOP良好实践的角度来看,我不确定这种方法是否值得推荐。

也许这就是您想要的。对于包含类的每个目录,运行::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);

它实际上和作曲家一样,只是不太适应或表演。

为此,您可以使用Composer:https://getcomposer.org/download/

您将得到一个名为composer.phar的文件。将其放在项目目录中,然后转到命令行上的该目录。

运行php composer.phar init

这会问你一些你可以忽略的问题,最后你会得到一个名为composer.json 的新文件

它应该看起来像这样:

{
    "autoload": {
        "psr-0": { "": "src/" }
    },
    "require": {}
}

添加autoload字段,并将src/替换为包含类的目录。请确保该目录存在。

然后运行php composer.phar install

这将创建一个名为vendor的目录。这个目录中有一个名为autoload.php的文件。

将此文件包含在项目的引导程序中,源目录中的所有类都将自动加载到中。

您研究过spl_autoload_register函数吗?

使用

// pre php 5.3
function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

然后将所有类放在"classes"文件夹中,当您使用new关键字初始化它们时,它们将自动包含在内。也适用于静态类。

例如:

$myClassOb1 = new MyClass();
// will include this file: classes/MyClass.class.php

$email = Utils::formatEmail($emailInput);
// will include this file: classes/Utils.class.php