简体   繁体   中英

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": "bar@example.com"
        }
    ],
    "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?

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

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

I believe

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

Should be:

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

So your file would be:

{
    "name": "vendor/sandbox",
    "authors": [
        {
            "name": "foo",
            "email": "bar@example.com"
        }
    ],
    "require": {
        "phpunit/phpunit": "dev-master",
        "phpunit/phpunit-mock-objects": "dev-master"
    },
    "autoload": {
        "psr-4": {
          "Sandbox\\": "src/"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM