PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, May 21, 2022

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

 May 21, 2022     autoload, composer-php, php     No comments   

Issue

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.


Solution

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.



Answered By - yivi
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing