How to Use Composer to Autoload Classes from Outside the Vendor

How to use Composer to autoload classes from outside the vendor?

The src directory would be in your project root.
Its on the same level as vendor directory is.

If you define

"autoload": {
"psr-4": {
"DG\\Munchkin\\": "src/DG/Munch/"
}
}

this will not load classes from /var/www/html/xxx/vendor/yyy/src/DG/Munch,
like you stated.

Because your project structure is:

/var/www/html/
+- /xxx (project)
- composer.json
+- /src
+- DG
+- Munch
+- /vendor
- autoload.php
+- vendor-projectA
+- vendor-projectB
+- yyy

The \DG\Munchkin namespace would map to classes inside

/var/www/html/xxx/src/DG/Munch and not inside

/var/www/html/xxx/vendor/yyy/src/DG/Munch.

But how can I load classes from /var/www/html/xxx/?

Define the paths in the composer.json (inside /var/www/html/xxx/) of your project:

"autoload": {
"psr-4": {
"ProjectRoot\\" : "",
"NamspaceInSourceDir\\" : "src/"
}
}

or load the composer autoloader in your index.php or during it's bootstrap and add the paths manually:

$loader = require 'vendor/autoload.php';
$loader->add('Namespace\\Somewhere\\Else\\', __DIR__);
$loader->add('Namespace\\Somewhere\\Else2\\', '/var/www/html/xxx');

Referencing: https://getcomposer.org/doc/04-schema.md#autoload

Composer Autoload Classes from outside vendor

Simple mistake. Change:

namespace Library\MyClass;

to

namespace Library;

Make sure you have ran composer dumpautoload too!

Cannot autoload class using composer from within other autoloaded class file

You're not using a FQCN of the Config class, but a name relative to App\Database namespace.

To fix this, you need to prefix the Config class with a \:

\App\Config\Config::GetDatabaseConfig();

or even better, you can import the Config class with use App\Config\Config; and then use it with Config::GetDatabaseConfig()

Load class from vendor folder inside autoloaded class from a folder outside vendor

This is a namespace issue. You need to either add:

use upload;

under the namespace declaration in you App\User-file to import the upload-class or you need to use the full namespace to the upload class when using it:

$handle = new \upload($file); 

You can read more about it in the manual

Note: In the posted code, $file is undefined when you're trying to use it in uploadImage()-function.

Note 2: If you've included vendor/autoload.php in the top of your index.php (which you should), there's no need to include the classes manually in PHP. Composers autoloader will handle that automatically. Just to: $user = new App\User.

Composer autoload not found classes psr4

You are doubling up a src level.

By ink\\ : src you are saying that anything after ink is in the src folder.

But your class is in a ink\src\classes\MyClass namespaces.

So this adds up to src+src/classes/MyClass=src/src/classes/MyClass path.

So you likely need:

{
autoload : {
psr-4 : {
ink\\src\\ : src
}
}
}


Related Topics



Leave a reply



Submit