2

我有以下文件结构:

src/Models/Entity.php 
vendor/*
index.php
composer.*

Entity.php 包含

<?php
namespace Vendor\App\Models;

class Entity {}

index.php 包含

<?php
namespace Vendor\App;

require 'vendor/autoload.php';

use Vendor\App\Models\Entity;

$entity = new Entity();

composer.json 包含:

{
    "autoload": {
        "psr-0": {"Vendor\\App\\": "src/"}
    }
}

供应商/作曲家/autoload_namespaces.php 包含

<?php

// autoload_namespaces.php generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'Vendor\\App\\' => $baseDir . '/src/',
);

我明白了127.0.0.1:37409 [500]: / - Class 'Vendor\App\Models\Entity' not found in ...

错误在哪里?composer.json 中复杂的命名空间和/或源目录的格式是什么?

更新:我找到了解决方法(将 src/Models 移动到 src/Vendor/App/Models),但这是正常行为吗?

4

1 回答 1

6

Composer/PSR-0 自动加载约定相当混乱。每次创建新的 Packagist 项目时,我都必须查找它。

当您创建 composer.json 文件并设置自动加载信息时,如下所示:

{
    "autoload": {
        "psr-0": { "Vendor\\App\\": "src/" }
    }
}

您要说的是“可以在project_root/src.内的另一个嵌套文件夹。

这就是为什么你需要把你的类放在project_root/src/Vendor/App这个自动加载方案中才能找到。

旁注:如果您碰巧在类名中使用了任何下划线,这也可能导致其工作方式出现问题,因为下划线还暗示嵌套文件夹(即App\Models\Type\Entity,指向 的src/App/Models/Type/Entity.php,被视为与 相同App/Models/Type_Entity.php)。所以要小心下划线!

于 2013-03-17T21:07:06.117 回答