简体   繁体   English

如何使用 Composer 的自动加载器自动加载 composer.json 中未配置的任意类/命名空间?

[英]How to use Composer's autoloader to autoload arbitrary classes/namespaces not configured in composer.json?

For reasons that are unimportant (let's just call it an intellectual curiosity) I'm trying to use Composer's autoloader to load a package not in composer.json / composer.lock .出于不重要的原因(我们称之为求知欲),我正在尝试使用 Composer 的自动加载器加载不在composer.json / composer.lock中的 package 。

Here's what I've tried:这是我尝试过的:

$loader = new \Composer\Autoload\ClassLoader();
$loader->addPsr4('MyNameSpace\\', __DIR__ . '/vendor/username/projectname/src');
$loader->register();

Unfortunately, this isn't working.不幸的是,这不起作用。 Whenever I try to do use MyNameSpace\Whatever; $a = new Whatever;每当我尝试use MyNameSpace\Whatever; $a = new Whatever; use MyNameSpace\Whatever; $a = new Whatever; I get an error about how Whatever can't be found.我收到有关无法找到Whatever的错误消息。

With this file structure:使用此文件结构:

在此处输入图像描述

Where class Test1 is:其中 class Test1是:

// out/Test1.php
class Test1
{
    public function foo(): string 
    {
        return "foo bar baz";
    }
}

and class FooBar/Console/Test2 is:和 class FooBar/Console/Test2是:

// psr4/someroot/Console/Test2
namespace FooBar\Console;

class Test2
{
    public function bar(): string
    {
        return "fizz buzz";
    }
}

and having this on the test script ( test.php )并将其放在测试脚本中( test.php

// test.php

require __DIR__ . '/vendor/autoload.php';
$loader = new \Composer\Autoload\ClassLoader();

$loader->add('Test1', __DIR__ . '/out');
$loader->addPsr4('FooBar\\', __DIR__ . '/psr4/someroot');

$loader->register();

$t1 = new Test1();
$t2 = new \FooBar\Console\Test2();

echo $t1->foo(), "\n";
echo $t2->bar(), "\n";

I can run php test.php perfectly fine.我可以完美地运行php test.php

So something else must be misconfigured in your project.因此,您的项目中一定有其他配置错误。 Use the above example as a guide to fix it.使用上面的示例作为修复它的指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM