autoload.php应该包含在类文件中吗?

时间:2015-11-20 23:31:03

标签: php composer-php autoload plivo

我们正在使用这个plivo软件包:https://github.com/plivo/plivo-php并且当前版本引发了一个错误,因为它无法在类文件的顶部找到他们需要的自动加载文件。

<?php
namespace Plivo;
require 'vendor/autoload.php';
use Guzzle\Http\Client;
class PlivoError extends \Exception {}

根据我的经验,自动加载文件只应包含在实际调用类和函数的页面中。

这是他们的错误还是我们可以通过composer updates在我们自己的项目中解决这个问题。

2 个答案:

答案 0 :(得分:1)

现在已经修复了我对此库的拉取请求。

确实在包本身中引用任何作曲家自动加载是错误的。 Composer将安装一个全局可用的自动加载器,可以加载任何composer.json描述中包含的每个类。

答案 1 :(得分:1)

所以我创建了一个新目录来测试它:

[~/Code/plivo/php]$ mkdir composer_testing
[~/Code/plivo/php]$ cd composer_testing/

并初始化了一个没有依赖项的新composer.json文件:

[~/Code/plivo/php/composer_testing]$ composer init


Welcome to the Composer config generator 



This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [charlie/composer_testing]: 
Description []: 
Author [Charlie Chrisman <charlie@plivo.com>]: 
Minimum Stability []: 
Package Type []: 
License []: 

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? n
Would you like to define your dev dependencies (require-dev) interactively [yes]? n

{
    "name": "charlie/composer_testing",
    "authors": [
        {
            "name": "Charlie Chrisman",
            "email": "charlie@plivo.com"
        }
    ],
    "require": {}
}

Do you confirm generation [yes]? 

然后需要plivo-php库(具有require 'vendor/autoload.php';行)

[~/Code/plivo/php/composer_testing]$ composer require plivo/plivo-php
Using version ^1.0 for plivo/plivo-php
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing symfony/event-dispatcher (v2.7.6)
Loading from cache

- Installing guzzlehttp/guzzle (v3.8.1)
Loading from cache

- Installing plivo/plivo-php (v1.0.0)
Loading from cache

symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/event-dispatcher suggests installing symfony/http-kernel ()
Writing lock file
Generating autoload files
[~/Code/plivo/php/composer_testing]$

这是更新的composer.json文件:

{
    "name": "charlie/composer_testing",
    "authors": [
        {
            "name": "Charlie Chrisman",
            "email": "charlie@plivo.com"
        }
    ],
    "require": {
        "plivo/plivo-php": "^1.0"
    }
}

然后编写了一个简单的php文件,用于生成文本到语音XML:

<?php

require __DIR__ . '/vendor/autoload.php';

$r = new Plivo\Response();

$message = "Testing Plivo";
$params = array(
    'language' => "en-US",
    'voice' => 'WOMAN'
);

$r->addSpeak($message, $params);
Header('Content-type: text/xml');
echo($r->toXML());

?>

并正确输出预期的XML

<Response>
    <Speak language="en-US" voice="WOMAN">Testing Plivo</Speak>
</Response>

为什么它适合我而不适合你?