简体   繁体   中英

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 .

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; I get an error about how Whatever can't be found.

With this file structure:

在此处输入图像描述

Where class Test1 is:

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

and class FooBar/Console/Test2 is:

// 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

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.

So something else must be misconfigured in your project. Use the above example as a guide to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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