phpnamespacesautoloadpsr-4

namespace autoload not working in mvc php


I was having name conflicts so decided to use namespaces but I'm encountering an issue while attempting to implement a namespace using psr-4 autoload. I watched couple of videos to learn and tried this as I have never used it before. Please help to fix it

The specific error I'm facing is:

Fatal error: Uncaught Error: Class "App\Controllers\BaseController" not found in C:\xampp\htdocs\project\app\controllers\home.php:8 Stack trace: #0 C:\xampp\htdocs\project\app\core\app.php(20): require_once() #1 C:\xampp\htdocs\project\index.php(9): App\Core\App->__construct() #2 {main} thrown in C:\xampp\htdocs\project\app\controllers\home.php on line 8

baseController.php

namespace App\Controllers;
use App\Core\CSRFHelper;
use App\Models\Settings;
use App\Models\Category;
use App\Models\Language;
class BaseController extends Controller {

home.php

namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\User;
class Home extends BaseController {

this is my composer.json

{
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}

init.php

<?php

require_once 'app/vendor/autoload.php';
require_once 'app/core/session.php';
require_once 'app/core/config.php';
require_once 'app/core/controller.php';
require_once 'app/core/functions.php';
require_once 'app/core/database.php';
require_once 'app/core/idatabase.php';
require_once 'app/core/app.php';
require_once 'app/core/CSRFHelper.php';

?>

index.php

require_once 'app/init.php';
use App\Core\App;
$app = new App();

this is structure

    ├── app
    │   ├── controllers
    │   │   ├── BaseController.php
    │   │   ├── textTranslator.php
    │   │   └── home.php
    │   ├── core
    │   │   └── config.php
    │   │   ├── Controllers.php   
    │   │   ├── database.php
    │   │   └── app.php
    │   ├── models
    │   │   └── languages.php
    │   ├── libs
    │   ├── views
    │   ├── vendor
    │   │   ├── composer 
    │   │   └── autoload.php
    │   ├── composer.json
    │   ├── .htaccess
    │   └── init.php   
    ├── assets
    │   ├── css
    │   ├── fonticons
    │   ├── js
    │   └── json
    ├── .htaccess
    └── index.php

Solution

  • Depending on your point of view, you are using wrong namespaces.

    App\Controllers instead App\controllers.

    Or you are using wrong name for folders.

    app/controllers instead app/Controllers

    Be careful with upper and lower case letters.