PHP 编辑器自动加载器不会加载包含路径中的文件



假设有两个项目"project_a"和"project_b"。我正在通过set_include_path在索引中动态设置包含路径.php project_a以便能够使用位于文件夹/用户/我/开发/project_b/控制器中的project_b文件。

project_a的索引.php内容为:

set_include_path(get_include_path().':/Users/Me/develop/project_b');
require 'vendor/autoload.php';
$c = new projectbnsControllerMyController();

composer.json 内容是:

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

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

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

但是当我调用project_a的索引时.php我只收到此错误:

Fatal error: Uncaught Error: Class 'projectbnsControllerMyController' 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

我错过了什么?

提前感谢,大卫。

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

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

您的目录结构应为:

    - 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 LibraryLibsBootstrap 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();
?>

引导.php

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

作曲家.json

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

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

问候!

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

composer dumpautoload -o 

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

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

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

最新更新