使用 PSR4 自动加载 Composer

Composer autoloading with PSR4

可能是一些微不足道的事情,但我对基本的自动加载有疑问。我想创建沙盒项目只是为了测试新的解决方案,所以我创建了以下结构:

Sandbox
|- index.php
|- composer.json
|- vendor
|  |- {autogenerated content}
|- src
   |- Working.php

文件 composer.json 看起来像这样:

{
    "name": "vendor/sandbox",
    "authors": [
        {
            "name": "foo",
            "email": "bar@example.com"
        }
    ],
    "require": {
        "phpunit/phpunit": "dev-master",
        "phpunit/phpunit-mock-objects": "dev-master"
    },
    "psr-4": {
        "Sandbox\": "src/"
    }
}

当然我已经运行composer.update改了。然后写了一个琐碎的正文Working.php:

<?php

namespace Sandbox;

class Working
{
    public function __construct() {
        echo "Hello World";
    }
}

当然还有index.php

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Sandbox\Working;

new Working();

?>

我检查了这些文件的权限只是为了确定,但是当我尝试 运行 我得到

PHP Fatal error:  Class 'Sandbox\Working' not found in /var/www/Sandbox/index.php on line 6

我意识到这可能是微不足道的,但这里有什么问题吗?

您的 composer.json 缺少 autoload 密钥。 应该是

"autoload": {
    "psr-4": {
        "Sandbox\": "src/"
    }
}

我相信

"psr-4": {
        "Sandbox\": "src/"
    }

应该是:

"autoload": {
    "psr-4": {
      "Sandbox\": "src/"
    }

因此您的文件将是:

{
    "name": "vendor/sandbox",
    "authors": [
        {
            "name": "foo",
            "email": "bar@example.com"
        }
    ],
    "require": {
        "phpunit/phpunit": "dev-master",
        "phpunit/phpunit-mock-objects": "dev-master"
    },
    "autoload": {
        "psr-4": {
          "Sandbox\": "src/"
    }
}