I am trying to put all the peaces together I found about autoloading a class in composer but I can't make it work. Every example I see is missing some part. Basically it comes down to two files with 4 lines:
index.php
$loader = require 'vendor/autoload.php';
$loader->add('Vendor\\', __DIR__.'/../app/');
new Vendor_Package_Obj();
app/Vendor/Package/Obj.php
class Obj {}
I also tried psr-4 and all thinkable combinations of folders and names for `Vendor Package Obj? but no luck finding a working solution.
How can I autoload a file with composer using any of those standards?
According to PSR-4, The fully qualified class name MUST have a top-level namespace name, also known as a "vendor namespace" and underscores have no special meaning in any portion of the fully qualified class name.
Try this:
cd ~
mkdir -p testproj/src/MyApp/Package
cd testproj
composer init && composer update
Create your index.php with this content:
<?php
$loader = require 'vendor/autoload.php';
$loader->add('MyApp\\', __DIR__.'/src/');
$a = new MyApp\Package\Obj();
var_dump($a);
And put the Obj class (src/MyApp/Package/Obj.php) :
<?php
namespace MyApp\Package;
class Obj
{}
Now when you run the code:
php index.php
You should get this as output:
class MyApp\Package\Obj#2 (0) {
}
Also directory scaffolding should look like this:
testproj
├── composer.json
├── index.php
├── src
│ └── MyApp
│ └── Package
│ └── Obj.php
└── vendor
├── autoload.php
└── composer
├── ClassLoader.php
├── autoload_classmap.php
├── autoload_namespaces.php
├── autoload_psr4.php
└── autoload_real.php
来源:https://stackoverflow.com/questions/28046052/composer-autoload-full-example