Composer is not loading my own psr-0 files

4.3k views Asked by At

I can't seem to get composer to work with my own classes/files using the psr-0 autoload mechanism. Can anyone please shed some light as to why the below isn't working?

I'm getting the following output in my error log:

PHP Fatal error: Class 'TestdirTest1' not found in /home/webroot/bitlama/index.php on line 5

It does work If I uncomment the explicit require statement (index.php:2).

And if anybody is wondering - yes I have run composer install in the form of: 'php ../composer.phar install'.

This is my directory structure:

├── composer.json
├── index.php
├── testspacedir
│   └── Testdir
│       └── test1.php
└── vendor
    ├── autoload.php
    └── composer
        ├── autoload_classmap.php
        ├── autoload_namespaces.php
        ├── autoload_real.php
        └── ClassLoader.php

composer.json:

{
    "autoload": {
        "psr-0": { "Testdir\\": "testspacedir/"}
    }
}

test1.php:

<?php

namespace Testdir;

class Test1 {

    public function __construct()
    {
        echo "Woohoo Test1";
    }

}

index.php:

<?php
require 'vendor/autoload.php';
//require 'testspacedir/Testdir/test1.php';

$test1 = new Testdir\Test1();

vendor/autoload.php:

<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit7b4760e0f7ca9d6454dd2f098c374ba4::getLoader();
2

There are 2 answers

0
Chris Stryczynski On BEST ANSWER

My class file was named as test1.php instead of the required PSR-0 naming convention of Test1.php.

4
SamV On

You say it works because you removed require 'testspacedir/Testdir/test1.php'; and that is correct.

Since you defined the namespace -> folder structure in the autoload in composer.json, the vendor/autoload.php handles the loading of these folder(s) for you.

Take a look inside that vendor/autoload.php file and you will see for yourself.

To sum it up, composer handles the autoloading of the files for you so you don't have to perform these includes. Here is a snippet from http://getcomposer.org/doc/01-basic-usage.md#autoloading

Note: Composer provides its own autoloader. If you don't want to use that one, you can just include vendor/composer/autoload_namespaces.php, which returns an associative array mapping namespaces to directories.