Search code examples
phpcomposer-phpautoloaderpsr-4

PHP Composer Autoloader Simple Structure


I have Composer working and I'd like to use its autoloader to load my classes, but it's not working. Here's my directory structure. I'm keeping it really simple to start with.

index.php
composer.json
Vendor
controllers/webgl.php

Inside webgl.php I have:

namespace controllers;

class webgl {
    public function lesson1() {

    }
}

In index.php I have:

require('vendor/autoload.php');
//require_once('controllers/webgl.php');

$webglController = new \controllers\webgl;

And my composer.json defines this for autoloading:

"autoload": { 
    "psr-4": { 
        "controllers\\": "controllers/" 
    } 
}

If I uncomment the second require, the script works, otherwise I get "Fatal error: Class 'controllers\webgl' not found in /vagrant/index.php on line 5".

I thought that the folder structure, class namespace and class name all conformed to psr-4. But I must be misunderstanding something. I've read loads of similar questions but none have been able to sort it for me.

Can anyone tell me why my class isn't loading and what I should do to fix it?


Solution

  • Did you define an autoload directive?

    You need to add this to your composer.json file:

    "autoload": {
        "psr-4": {
            "controllers\\": "controllers/"
        }
    }
    

    to point the autoloader in the right direction and then run

    composer update  
    

    from the terminal in your project directory. Now the class will load without explicitly requiring its file.