Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we initialize a class object inside the config file?

Is it a good practice to initialize an object for an authentication class that does various stuff like register user, login user etc. inside a config file?

The config file mostly does stuff like setting db username, password and site name etc.

Please provide a reason if you don't find this a standard practice. Just to let you know most of the code is procedural except for this particular class.

    // MySQL connection settings
    $db_host = "localhost";
    $db_user = "someuser";
    $db_pass = "some pass";
    $db_name = "somedb";



    // Name of the site
    $site_name = "MyDomainName";   



    $auth = new auth();//initialize Authentication class
$auth->set_auth();//Check if user autorized
like image 218
user481913 Avatar asked Feb 01 '26 11:02

user481913


2 Answers

In my opinion this is not a good idea. A config file is for configuration, not for execution. I would put this code into a bootstrap.php, so, when you have to edit your code in the future, you know exactly where you can find your configurations and instantiations.

index.php:

include('bootstrap.php');

bootstrap.php:

include('config.php');
$auth = new auth();
$auth->set_auth();

config.php:

$db_host = "localhost";
$db_user = "someuser";
$db_pass = "some pass";
$db_name = "somedb";
like image 187
Sascha Galley Avatar answered Feb 03 '26 02:02

Sascha Galley


The authentication class should be responsible for authenticating, not handling user-specific functions like register/edit/delete. The config object should be available to object needing the configuration data, not the other way around.

The config file should not contain anything other then config data.

like image 23
Wesley van Opdorp Avatar answered Feb 03 '26 02:02

Wesley van Opdorp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!