2

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
4
  • 1
    Think "Blog\\": "app/classes/Database" should be "Blog\\": "app" as the namespace acts as the path to find the class. Commented Mar 21, 2018 at 8:01
  • Hi @NigelRen . I'll try it Commented Mar 21, 2018 at 8:03
  • @NigelRen . I think I just ask a stupid question. It is now working man. Commented Mar 21, 2018 at 8:05
  • 1
    I'm sure I've asked loads of stupid questions, main thing is to learn from them. Commented Mar 21, 2018 at 8:07

2 Answers 2

2

In your composer.json

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

should be

"Blog\\": "app" 

as the namespace acts as the path to find the class

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @NigelRen . One more thing. What I only want the Database folder?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.