php 作曲家自动加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20181181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Composer Autoloading
提问by James Jeffery
I'm currently trying to use PSR-0 autoloading with Composer, but I'm getting the following error:
我目前正尝试在 Composer 中使用 PSR-0 自动加载,但出现以下错误:
Fatal error: Class 'Twitter\Twitter' not found
My directory structure looks like this
我的目录结构是这样的
- Project
- src
- Twitter
Twitter.php
- vendor
- Test
index.php
My index.php file looks like this:
我的 index.php 文件如下所示:
<?php
use Twitter;
$twitter = new Twitter();
My Twitter.php file looks like this
我的 Twitter.php 文件看起来像这样
<?php
namespace Twitter;
class Twitter
{
public function __construct()
{
// Code Here
}
}
And finally my composer.json looks like this:
最后我的 composer.json 看起来像这样:
{
"require": {
"phpunit/phpunit": "3.8.*@dev",
"guzzle/guzzle": "3.7.*@dev"
},
"minimum-stability": "dev",
"autoload": {
"psr-0": {
"Twitter" : "src/Twitter"
}
}
}
I am getting a little confused. I come from a C# background and this way of working is kinda confusing me. What's the correct way to use PSR-0 autoloading?
我有点困惑。我来自 C# 背景,这种工作方式让我有点困惑。使用 PSR-0 自动加载的正确方法是什么?
回答by Gianluca Mancini
In your composer.json use:
在您的 composer.json 中使用:
"autoload": {
"psr-0": {
"": "src/"
}
}
or
或者
"autoload": {
"psr-0": {
"Twitter\": "src/"
}
}
and then run php composer.phar dump-autoload
然后运行 php composer.phar dump-autoload
回答by dev-null-dweller
Use
用
"psr-0": {
"Twitter" : "src/"
}
This instructs composer to create autoloader, that will look in srcfor everything from Twitternamespace. And since it is PSR-0, namespace is treated as a folder and added to declared path, so you should not include it in path part in composer.json
这指示作曲家创建自动加载器,它将src从Twitter命名空间中查找所有内容。既然是这样PSR-0,命名空间被视为一个文件夹并添加到声明的路径中,因此您不应将其包含在路径部分composer.json
回答by abuduba
First of all,
首先,
My index.php file looks like this:
use Twitter; $twitter = new Twitter();
我的 index.php 文件如下所示:
use Twitter; $twitter = new Twitter();
If it's your index.php you forgot to include the composer's autoload script first.
如果它是您的 index.php,则您忘记首先包含作曲家的自动加载脚本。
require __DIR__ . '/vendor/autoload.php';
See https://getcomposer.org/doc/01-basic-usage.md#autoloadingfor details.
有关详细信息,请参阅https://getcomposer.org/doc/01-basic-usage.md#autoloading。
回答by Quim Calpe
There is an error in your index.php, should be:
use Twitter\Twitter;
$twitter = new Twitter();
or
$twitter = new Twitter\Twitter();
你的 index.php 有错误,应该是:
use Twitter\Twitter;
$twitter = new Twitter();
或
$twitter = new Twitter\Twitter();
回答by barudo
This is a very late reply but the first thing you need to make "autoloading" works is have your PHP version be 5.6 and above.
这是一个很晚的回复,但您需要使“自动加载”工作的第一件事是让您的 PHP 版本为 5.6 及更高版本。

