Composer autoload full example?

一个人想着一个人 提交于 2019-12-31 16:33:17

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!