Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PSR-4 autoloader Fatal error: Class not found

I have my project structure like so:

src/
   ├─ Model/
      └─ User.php

My User.php file looks like this:

<?php
namespace Bix\Model;

class User {

And my composer.json autoloader is this:

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

Finally my bootstrap.php is this:

use Bix\Model\User;

// PSR-4 Autoloader.
require_once "vendor/autoload.php";

However if I try and create a new User(), I get the error Fatal error: Class 'User' not found in /var/www/public/api/v1/index.php on line 8

Looking at the composer autoload_psr4.php file it looks ok:

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));

return array(
    'XdgBaseDir\\' => array($vendorDir . '/dnoegel/php-xdg-base-dir/src'),
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'KeenIO\\' => array($vendorDir . '/keen-io/keen-io/src'),
    'Bix\\' => array($baseDir . '/src'),
); 

Can anybody point out where I am going wrong with the above?

like image 553
JeremyKirkham Avatar asked May 09 '15 06:05

JeremyKirkham


Video Answer


1 Answers

First of all, Linux (I'm not sure which PC you use) is case-sensitive. In your autoloading, you defined src/bix, while it is src/Bix.

But more importantly, with PSR-4, the specified namespace prefix is not included in the directory structure (to avoid directories containing just one directory). In your case, if you configure "Bix\\": "src/", a class Bix\Model\User should be located in src/Model/User.php.


EDIT: You're misunderstanding PHP namespaces. In PHP, you're not saying "import everything from Bix\Model into the global namespace for this file" with use Bix\Model;. Instead, it means: "Alias Model in this file to Bix\Model".

So you should either do:

require_once "vendor/autoload.php";

use Bix\Model;

$user = new Model\User();

or:

require_once "vendor/autoload.php";

use Bix\Model\User;

$user = new User();
like image 123
Wouter J Avatar answered Sep 22 '22 21:09

Wouter J