How to manage inclusions, requirements, and usage in this project
P粉652495194
P粉652495194 2024-02-25 18:11:04
0
1
364

In this PHP project without a framework, I have this folder structure: Adapters, Classes and Models

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

Index file

<?php

    include('Class/Load.php');

    $connection = MysqlClass::getConnectionMysql();

Class loading

<?php

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

Mysql class 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 problem is in the second MysqlClass file, should I include the file here into the different classes I need or should I do this in the index.php file of the load.php file Action and from there load all the classes I need in the rest of the project.

P粉652495194
P粉652495194

reply all(1)
P粉242535777

It's always a good idea to use an autoloader, such as Composer.

First, move the Adapter, Class and Models subdirectories to the src directory. Completely remove Load.php.

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 home directory:

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

In all class files, place the correct namespace and remove all include and require calls:


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


Now you can call this code from anywhere and the class will be loaded if needed:

use Acme/Class/MysqlClass

// ...

$connection = MysqlClass::getConnectionMysql();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template