0
votes

I'm new to using composer for autoloading custom class files using 'PSR-0' way of autoloading classes.

Below is my directory tree structure.

Folder Structure

And below is my PSR-0 config in the composer.json file

enter image description here

Class autoloading is fine when requested from outside my project file after requiring the vendor/autoload.php

The problem is when trying to load a class from within another class with a defined namespace.

Example:

I am trying to call a static method ::GetDatabaseConfig() from the Config class within the Config folder into the Database class within the Database folder. This is the code I'm using inside the Database class.

Database/Database.php

namespace App\Database;
class Database{
    public static $con;
    public static $connected = false;
    public static $error = false;
    public static $error_message = "";

    function __construct( $opt=false ){
        $config = App\Config\Config::GetDatabaseConfig();
        //REST....
    }
}

This code doesn't work and displays this error.

Fatal error: Uncaught Error: Class "App\Database\App\Config\Config" not found in /storage/emulated/0/code/durandal/htdocs/api/idan/App/Database/Database.php:13

I see that the namespace used in the Database.php file is used as a prefix when requesting App\Config\Config class.

What is it that I'm missing here? How to resolve it?

1
Are you using PSR-0 and not PSR-4 for any particular reason? - yivi
It's just that it forces me to stay strictly organised with my directory and file structure. - Danish Nayeem
Why not properly import the classes using a use statement? If you want to skip the use, you have to use an absolute path to the class like \App\Config\Config::GetDatabaseConfig (with a backslash in the front) - Nico Haase
Yup. That's what I'm doing now. - Danish Nayeem

1 Answers

2
votes

You're not using a FQCN of the Config class, but a name relative to App\Database namespace.

To fix this, you need to prefix the Config class with a \:

\App\Config\Config::GetDatabaseConfig();

or even better, you can import the Config class with use App\Config\Config; and then use it with Config::GetDatabaseConfig()