phpcomposer-phpautoloaderset-include-path

PHP Composer autoloader does not load files in include path


Assume there are two projects "project_a" and "project_b". I am setting the include path dynamically in index.php of project_a via set_include_path to be able to use the files of project_b lying in folder /Users/Me/develop/project_b/controller.

project_a's index.php content is:

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

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

composer.json content is:

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

And finally the content of MyController.php in project_b is:

namespace projectbns\Controller;

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

But when I call project_a's index.php I only get this error:

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

What am I missing?

Thanks in advance, David.

P.S.: Yes I have to set the include path dynamically for specific reasons.


Solution

  • I now solved my problem by setting up "an own composer" in project b (project_b gets its own composer.json, then in terminal: composer install). This has the effect that composer will generate a vendor/autoload.php file in project b which can be required in project a via absolute path:

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

    This way no include path modifications are needed and project b can handle autoloading its classes by itself (which seems a little bit more modular to me).