phpphp-7php-7.2php-7.4php-7.3

How to manage includes, require and use in this project


In this PHP project without framework, I have this folder structure: Adapter, Class and Models

A php file "index.php" is executed from the root and I have problems handling the model and adapter classes

Index file

<?php

    include('Class/Load.php');

    $connection = MysqlClass::getConnectionMysql();

Class Load

<?php

    include(__DIR__ . DIRECTORY_SEPARATOR . 'MysqlClass.php');
    include(__DIR__ . DIRECTORY_SEPARATOR . 'UtilsClass.php');
    include(__DIR__ . DIRECTORY_SEPARATOR . 'EmailClass.php');

MysqlClass File

<?php

include ('UtilsClass.php');


class MysqlClass
{


    /**
     * @return PDO
     */
    public static function getConnectionMysql(): PDO
    {

        $dbhost = ReadEnvFileClass::getConfig('MYSQL_LOCAL_HOST');
        $dbuser = ReadEnvFileClass::getConfig('MYSQL_LOCAL_USER');
        $dbpass = ReadEnvFileClass::getConfig('MYSQL_LOCAL_PWD');
        $dbname = ReadEnvFileClass::getConfig('MYSQL_LOCAL_DBNAME');
        
        try {
            $dsn = "mysql:host=$dbhost;dbname=$dbname";
            $dbh = new PDO($dsn, $dbuser, $dbpass);
        } catch (PDOException $e){

            var_dump($dbhost,$dbuser,$dbpass);
            echo $e->getMessage();
        }

        return $dbh;
    }


}

The question is in this second MysqlClass file if I should include here the files to the different classes that I need, or should I do it in the index.php file from a load.php file and from there load all the classes that I need in the rest of the project .


Solution

  • It is always a good idea to use an autoloader, like the one provided by Composer.

    First, move Adapter, Class and Models subdirectories under a directory src. Remove Load.php completely.

    The structure will be:

    index.php
    composer.json
    src/Class/MysqlClass.php
    src/Class/UtilsClass.php
    src/Class/EmailClass.php
    src/Adapter/...
    src/Models/...
    

    Then create the composer.json file in the main directory:

    {
        "autoload": {
            "psr-4": {"Acme\\": "src/"}
        }
    }
    

    In all class files, put the proper namespace and remove all include and require calls:

    <?php
    
    namespace Acme/Class
    
    class MysqlClass {
    // ...
    

    Run composer install or just composer dump-autoload in the main directory, and include the autoload.php file in your index.php (remove all other includes and requires).

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    

    Now you can call this code from any place, the class will be loaded if needed:

    use Acme/Class/MysqlClass
    
    // ...
    
    $connection = MysqlClass::getConnectionMysql();