PHP Composer 自动加载器不加载包含路径中的文件

PHP Composer autoloader does not load files in include path

假设有两个项目 "project_a" 和 "project_b"。我正在通过 set_include_path 在 project_a 的 index.php 中动态设置包含路径,以便能够使用位于文件夹 [=35= 中的 project_b 的文件].

project_a的index.php内容是:

set_include_path(get_include_path().':/Users/Me/develop/project_b');
require 'vendor/autoload.php';

$c = new projectbns\Controller\MyController();

composer.json内容为:

{
    "require": {},
    "autoload": {
        "psr-4": {
            "projectbns\Controller\": "controller/"
        }
    },
    "config": {
        "use-include-path": true
    }
}

最后project_b中MyController.php的内容是:

namespace projectbns\Controller;

class MyController {
    public function __construct() {
        die(var_dump('Hi from controller!'));
    }
}

但是当我调用 project_a 的 index.php 时,我只得到这个错误:

Fatal error: Uncaught Error: Class 'projectbns\Controller\MyController' not found in /Users/Me/develop/project_a/index.php:8 Stack trace: #0 {main} thrown in /Users/David/Me/develop/project_a/index.php on line 8

我错过了什么?

提前致谢, 大卫.

P.S.: 是的,出于特定原因我必须动态设置包含路径。

好的,所以 尝试将 psr-4 更改为 psr-0 然后

composer dumpautoload -o 

这是简单的工作演示。希望你喜欢我的东西。

你的目录结构应该是:

    - Main
        - index.php
        - composer.json
        - vendor
        - Libs
            - botstrap.php

index.php :初始第一个登陆文件(根目录)

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);

    // Include autoloading file
    require "vendor/autoload.php";

    // User target class file namespace
    use Library\Libs\Bootstrap as init;

    // Create object of the bootstrap file.
    $bootstrap = new init();

    /*
     * Object of the bootstrap file will call constructor by default.
     * if you want to call method then call with bellow code
     */

    $bootstrap->someFunc();

?>

Bootstrap.php

<?php
    namespace Library\Libs;

    class Bootstrap {
        function __construct() {
            echo "Class Construcctor called..<br/>";
        }
        public function someFunc()
        {
            echo "Function called..:)";
        }
    }
?>

composer.json

    {
    "name": "root/main",
    "autoload": {
        "psr-4": {
            "Library\Libs\": "./Libs",
        }
    }
}

毕竟不要忘记转储自动加载。 希望对您有所帮助。

您好!

我现在通过在项目 b 中设置 "an own composer" 解决了我的问题(project_b 得到了自己的 composer.json,然后在终端中: 作曲家安装)。这具有作曲家将在项目 b 中生成一个 vendor/autoload.php 文件的效果,该文件可以通过绝对路径在项目 a 中被要求:

require_once '/Users/Me/develop/project_b/vendor/autoload.php';

这样就不需要对包含路径进行修改,并且项目 b 可以自行处理其 类 的自动加载(对我来说这似乎更加模块化)。