作曲家自动加载完整示例? [英] Composer autoload full example?
问题描述
我正在尝试放置全部 豌豆 一起我发现了有关自动加载在作曲家上课,但我无法使其正常工作.我看到的每个示例都缺少某些部分.基本上可以归结为4行的两个文件:
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
index.php
$loader = require 'vendor/autoload.php';
$loader->add('Vendor\\', __DIR__.'/../app/');
new Vendor_Package_Obj();
app/Vendor/Package/Obj.php
app/Vendor/Package/Obj.php
class Obj {}
我还尝试了psr-4以及文件夹和名称的所有可想像的组合,以用于`Vendor Package 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.
如何使用任何这些标准通过composer自动加载文件?
How can I autoload a file with composer using any of those standards?
推荐答案
根据 PSR -4 ,完全合格的类名称必须具有顶级名称空间名称,也称为供应商名称空间",并且下划线在完全合格的类名称的任何部分都没有特殊含义.
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.
尝试一下:
cd ~
mkdir -p testproj/src/MyApp/Package
cd testproj
composer init && composer update
使用以下内容创建index.php:
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);
并放入Obj类(src/MyApp/Package/Obj.php):
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
您应该将此作为输出:
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
这篇关于作曲家自动加载完整示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!