1
votes

I'm trying to implement the autoload feature using psr-4 with composer but I get this error, even if I've already require it in the index. Please see the error and code below:

Error

Fatal error: Class 'Blog\Classes\Database\Connection' not found in C:\wamp\www\blog-oop\index.php on line 7

Code

composer.json

{
    "autoload": {
        "psr-4": {
            "Blog\\": "app/classes/Database"
        }
    }
}

Connection.php

<?php

namespace Blog\Classes\Database;

class Connection{


}

index.php

<?php

require "vendor/autoload.php";

use Blog\Classes\Database\Connection;

$connection = new Connection;

Structure

>app 
  >classes
    >Database
      >Connection.php
2
Think "Blog\\": "app/classes/Database" should be "Blog\\": "app" as the namespace acts as the path to find the class. - Nigel Ren
Hi @NigelRen . I'll try it - Jie
@NigelRen . I think I just ask a stupid question. It is now working man. - Jie
I'm sure I've asked loads of stupid questions, main thing is to learn from them. - Nigel Ren

2 Answers

1
votes

In your composer.json

"Blog\\": "app/classes/Database" 

should be

"Blog\\": "app" 

as the namespace acts as the path to find the class

1
votes

i think the error occured in composer json

Instead of

"Blog\\": "app/classes/Database"

It should be

"Blog\\": "app/"

My composer.json test

{
    "name": "test",
    "description": "Test",
    "autoload": {
        "psr-4": {
            "Blog\\": "app/"
        }
    }
}

app/Classes/Database/Connection.php

<?php

namespace Blog\Classes\Database;

class Connection {
    public function __construct()
    {
        print_r('Connection class was called');
    }
}

Result:

Connection class was called