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 .
It is always a good idea to use an autoloader, like the one provided by Composer.
First, move
Adapter
,Class
andModels
subdirectories under a directorysrc
. RemoveLoad.php
completely.The structure will be:
Then create the
composer.json
file in the main directory:In all class files, put the proper namespace and remove all
include
andrequire
calls:Run
composer install
or justcomposer dump-autoload
in the main directory, and include theautoload.php
file in yourindex.php
(remove all other includes and requires).Now you can call this code from any place, the class will be loaded if needed: