'Is it possible to not use namespaces in some classies? I'm in trouble with autoload

I'm working with a old project. Classies have no namespacies.

Path structure:

-container         // Container
--app
----model          // all classies without namespace
----model_common   // all classies used by other two projects without namespace
------Rede         // new librarie with namespace
--------Exception
--------Service
----view
----controller

spl_autoload_register function is in a file named init_client.php, inside app path:

define('M_CMN', CLI_APP. 'model_common/');    // $_SERVER['DOCUMENT_ROOT'] . '/app/model_common/'
define('M_CLI', CLI_APP. 'model/');           //  $_SERVER['DOCUMENT_ROOT'] . '/app/model/'

function autoload_client($class){
    $path_and_class = str_replace('\\', DIRECTORY_SEPARATOR, $class); // May case there is a namespace
    
    if (file_exists(M_CMN . "{$path_and_class}.php")):      // First local to find class
        require_once M_CMN . "{$path_and_class}.php";
        
    elseif (file_exists(M_CLI . "{$path_and_class}.php")):
        require_once M_CLI . "{$path_and_class}.php";
   
    else :
        ErrorFunction("Class {$path_and_class} was not found.",ERROR_1);
    endif;
}
spl_autoload_register('autoload_client');

Example:

$consult = new DealConsult; // app/model $consult->checkTransaction('123') // It will use Rede\Store, Rede\Environment and Rede\eRede classies

Error: Class Rede/Store was not found. But file $_SERVER['DOCUMENT_ROOT'] . '/app/model/Rede/Store.php' exist.

DealConsult.php class:

use Rede\Store;
use Rede\Environment;
use Rede\eRede;

class DealConsult {
    public function checkTransaction($cod) {
            $this->store = new Rede\Store($_SESSION['trans']['id_filiacao'], $_SESSION['trans']['token'], Rede\Environment::sandbox());

            $this->transaction = (new Rede\eRede($this->store))->getByReference($cod);

            printf("Autorization status: %s\n", $this->transaction->getAuthorization()->getStatus());
    }

What am I not getting understand? I'm learning namespacies recently as well as PSR-4 defaults.

php


Solution 1:[1]

Use Composer to automatically load all the classes. In your composer.json file, you need to have:

{
    "autoload": {
        "psr-4": {
            "Rede\\": "container/app/model_common/"
            // Add as many classes as you need here in this map...
        }
    }
}

After that, run:

compose dump-autoload --optimize

Finally, include vendor/autoload.php where necessary.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 msrumon