我似乎无法让composer使用psr-0自动加载机制来处理我自己的类/文件。有人能解释一下为什么下面的不起作用吗?
我在错误日志中得到以下输出:
PHP致命错误:在中找不到类"TestdirTest1"/home/webroot/bitlama/index.php第5行
如果我取消对显式require语句(index.php:2)的注释,它确实有效。
如果有人想知道——是的,我已经以以下形式运行composer安装:"php/composer.phar安装'。
这是我的目录结构:
├── composer.json
├── index.php
├── testspacedir
│ └── Testdir
│ └── test1.php
└── vendor
├── autoload.php
└── composer
├── autoload_classmap.php
├── autoload_namespaces.php
├── autoload_real.php
└── ClassLoader.php
composer.json:
{
"autoload": {
"psr-0": { "Testdir''": "testspacedir/"}
}
}
test1.php:
<?php
namespace Testdir;
class Test1 {
public function __construct()
{
echo "Woohoo Test1";
}
}
index.php:
<?php
require 'vendor/autoload.php';
//require 'testspacedir/Testdir/test1.php';
$test1 = new Testdir'Test1();
vendor/autoload.php:
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit7b4760e0f7ca9d6454dd2f098c374ba4::getLoader();
我的类文件被命名为test1.php
,而不是Test1.php
所需的PSR-0命名约定。
你说它有效是因为你删除了require 'testspacedir/Testdir/test1.php';
,这是正确的。
由于您在composer.json
中的autoload
中定义了名称空间->文件夹结构,因此vendor/autoload.php
将为您处理这些文件夹的加载。
看看vendor/autoload.php
文件的内部,你会亲眼看到的。
总之,composer为您处理文件的自动加载,因此您不必执行这些include。以下是http://getcomposer.org/doc/01-basic-usage.md#autoloading
注意:Composer提供了自己的自动加载器。如果你不想使用那一个,你可以包括vendor/comporter/autoload_namespaces.php,返回关联将命名空间映射到目录的数组。