neubert
neubert

Reputation: 16792

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

Upvotes: 1

Views: 1326

Answers (1)

yivi
yivi

Reputation: 47329

With this file structure:

enter image description here

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.

Upvotes: 2

Related Questions