8

The title speaks itself. So here is my project structure:

|src
    |Database
        |Core
            |MySQL.php
        |Support
    start.php
|vendor
composer.json
index.php

MySQL.php file:

<?php
namespace Database\Core;
//Some methods here

index.php and start.php files:

//start.php file
<?php
require __DIR__ . '/../vendor/autoload.php';
?>

//index.php file
<?php
use Database\Core;
require __DIR__ . '/src/start.php';

$mysql = new MySQL(); // Gets exception Class 'MySQL' cannot found etc.
?>

And finally my composer.json autoload part:

"autoload": {
    "psr-4": "Database\\": "src/" // Also tried "src/Database" too
}

Where is the problem? I'm really tired of trying to cope with this situation. Please help guys! Thanks.

Populus
  • 7,470
  • 3
  • 38
  • 54
lostbyte
  • 466
  • 1
  • 8
  • 21

2 Answers2

21

You need to include namespace when you are initializing a class:

$mysql = new Database\Core\MySQL();

or

use Database\Core\MySQL;
$mysql = new MySQL();

See Using namespaces: Aliasing/Importing

Adi Prasetyo
  • 1,006
  • 1
  • 15
  • 41
Populus
  • 7,470
  • 3
  • 38
  • 54
6

Aside from not using the right use statement as already mentioned, PSR-4 does not work like that. It is more of an alias. You are essentially saying that src equals Database. So to have a directory named Database in there would imply that the fully qualified namespace + class equals 'Database\Database\Core\MySQL`. You want to use PSR-0 in this case, or adjust your PSR-4 definition.

alcohol
  • 22,596
  • 4
  • 23
  • 21
  • To expand a bit on this good answer: you wouldn't want your namespace to be something generic like "Database". You want to use something that no other php package might already use, so the name of your company/org is a good choice, e.g. if your company is named Acme Baseball Cards, a good namespace might be "AcmeBaseball". In your Mysql.php file then the namespace would be `namespace AcmeBaseball\Database\Core;` and in composer.json `"psr-4": "AcmeBaseball\\": "src/"` You'll notice this if you install a composer package like AWS Php SDK; open their compser.json and the namespace is `Aws` – KayakinKoder Apr 29 '17 at 22:39