Search code examples
phpcomposer-phpautoloadpsr-4

Composer autoloading with PSR4


Probably something trivial but I have a problem with basic autoloading. I wanna create sandbox project just for testing new solutions so I've created following structure:

Sandbox
|- index.php
|- composer.json
|- vendor
|  |- {autogenerated content}
|- src
   |- Working.php

File composer.json looks like this:

{
    "name": "vendor/sandbox",
    "authors": [
        {
            "name": "foo",
            "email": "[email protected]"
        }
    ],
    "require": {
        "phpunit/phpunit": "dev-master",
        "phpunit/phpunit-mock-objects": "dev-master"
    },
    "psr-4": {
        "Sandbox\\": "src/"
    }
}

Of course I've run composer.update after changes. Then I wrote a trivial body of Working.php:

<?php

namespace Sandbox;

class Working
{
    public function __construct() {
        echo "Hello World";
    }
}

And of course index.php as well:

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Sandbox\Working;

new Working();

?>

I checked permissions to those files just to be sure but when I try to run I get

PHP Fatal error:  Class 'Sandbox\Working' not found in /var/www/Sandbox/index.php on line 6

I realize it's probably something trivial but what can be wrong here?


Solution

  • At your composer.json you are missing autoload key. It should be like

    "autoload": {
        "psr-4": {
            "Sandbox\\": "src/"
        }
    }