【问题标题】:How to use __autoload function when use composer load使用 composer load 时如何使用 __autoload 函数
【发布时间】:2015-01-23 01:35:33
【问题描述】:
app/Core
contollers

这是我放置主类的网站结构,我使用 composer 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'; 它将起作用,所以我认为代码是正确的,我知道我可以在composer.json 中使用classmap,但是每次添加新类时都需要dump-autoload,如何处理冲突?

【问题讨论】:

    标签: php composer-php


    【解决方案1】:

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

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

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

    或者,您可以创建类映射

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

    附言实际上,您可以在 psr-4 中使用空命名空间。

    【讨论】:

    • classmap 需要一直运行composer dump-autoloadpsr-4 使用空字符串有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2017-11-23
    • 2018-02-01
    相关资源
    最近更新 更多