Robert Brax
Robert Brax

Reputation: 7318

Autoload: Class not found without removing require statements

Problem: I want to remove require statements from my code and use autoload instead. But when I do so, I have a class not found error:

Structure:

composer.json
index.php
users/user-model.php
users/users-route.php

Composer Json (I run composer dump-autoload) :

....  
"autoload": {
    "psr-4": {
      "User\\": "users/"
    }

Index.php:

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

//require ('users/user-model.php'); HERE: Doesn't work when I comment this

$klein = new \Klein\Klein();

require ('users/users-routes.php');

$klein->dispatch();

users-route.php:

use User\UserModel as user;

$klein->respond( 'GET', '/', function( $request, $response, $service, $app ) {
    $tt = new user();
    echo $tt::name();
} );

user-model.php:

namespace User;

class UserModel
{

    public static function name()
    {
        return 'bob';
    }
}

What should I change so I don't need : require ('users/user-model.php'); ?

Upvotes: 1

Views: 76

Answers (1)

shukshin.ivan
shukshin.ivan

Reputation: 11340

If you want to use autoload, do it in accordance with psr-4 as it is declared.

The file name MUST match the case of the terminating class name.

Rename the file to UserModel.php.

Upvotes: 1

Related Questions