如何在使用composer load时使用__autoload函数

时间:2014-11-25 06:27:22

标签: php composer-php

app/Core
contollers

这是我的网站结构,将主要类,我的用户作曲家psr-4规则导入到app/Core文件夹下的类。

composer.json

{
    "autoload": {
        "psr-4": {
            "Core\\": ["app/Core"]
        }
    }
}

的index.php

<?php

include 'vendor/autoload.php';

new Core/Api; // it's work

它工作正常,但我想在控制器文件夹下自动加载类 使用namespace,所以我使用__autoload函数:

的index.php

<?php

include 'vendor/autoload.php';

function __autoload($class_name) {
    include 'controllers/' . $class_name . '.php';
}


new Test // Fatal error: Class 'test'

如果我删除include 'vendor/autoload.php';它会有效,所以我认为代码是正确的,我知道我可以在classmap中使用composer.json,但每次都需要dump-autoload我添加了一个新类,如何处理冲突?

1 个答案:

答案 0 :(得分:3)

您不必使用自己的自动加载实现。您可以对所有类使用composer自动加载。

{
    "autoload": {
        "psr-0": { "": "src/" }
    }
}

https://getcomposer.org/doc/04-schema.md#psr-0

或者,您可以创建类地图

https://getcomposer.org/doc/04-schema.md#classmap

P.S。实际上,您可以使用空命名空间和psr-4。