0
votes

enter image description hereI am trying to understand the autoloading part with composer. Attached image is my project structure.

index.php

require __DIR__ . '/vendor/autoload.php';

// require "app/Controller/MyController.php"; // If i uncomment this my code is working fine. (only for testing purpose)

$mynamespace = new App\Controller\MyController();

$mynamespace->index();

composer.json

"psr-4": {
         "App\\": "app/" 
         }

MyController.php

namespace App\Controller;

class MyController{


    public function index(){
        echo "New  World";
    }
}

I ran composer dump-autoload and the file is not loaded.

How to map the autoloaded file via composer? I might go with multiple folders and files. So i prefer it to be one single directory as app/

enter image description here

2
What does your MyController.php file look like?cmorrissey
in addition have you run composer install ?cmorrissey
no change.. still i am getting class not foundAlaksandar Jesus Gene
How about your composer, can you updated it? Can you post the entire composer.json also?Gabriel Heming
I got it. I missed autoload in composer.json. Thanks for pointing to recheck the composer.jsonAlaksandar Jesus Gene

2 Answers

1
votes
{
    "name": "alaksandarjesus/testnamespace",
    "authors": [{
        "name": "alaksandarjesus",
        "email": "[email protected]"
    }],
    "require": {},
    "autoload": { // Missed this autoload and so it didnt load.
        "psr-4": {
            "App\\": "app"
        }
    }

}
0
votes

Off the top of my head, so not sure if helpful:

require __DIR__ . '/vendor/autoload.php';

use App\Controller\MyController;

$mynamespace = new MyController();

$mynamespace->index();

or possibly escape the top level namespace:

$mynamespace = new \App\Controller\MyController();