Herdy Herdy - 20 days ago 8
PHP Question

Composer psr-4 autoload cannot found file

I am still learning to use php composer

i have a directory structure like this :

Directory Structure

and this is my composer.json

{
"autoload": {
"psr-4": {
"Kct\\": "lib/"
}
}
}


Now in my index.php file i am trying to load Class tes in tesdir.php

<?php
// file: index.php

require __DIR__ . '/vendor/autoload.php';

$x = new \Kct\Tesdir\Tes();
var_dump($x->tes()); //output: 'GET'


my tesdir.php :

<?php
namespace Kct\Tesdir;

class Tes {

public function tes() {
return $_SERVER['REQUEST_METHOD'];
}

}


now if I open index.php in my localhost I got and error like this :

Fatal error: Uncaught Error: Class 'Kct\Tesdir\Tes' not found in /var/www/html/tesComposer/index.php:6 Stack trace: #0 {main} thrown in /var/www/html/tesComposer/index.php on line 6


can someone explain why.?

Answer

tesdir.php should be named Tes.php. The name of the file should match the name of the class.

See the PSR-4 examples