Working with classes and database connections

I am building a class that will handle all of my database record modifications (class SCFE_DB_mod)

Here is the current class:

	class SCFE_DB_mod{
				
		public function __construct(){	//initiate database connection
			require __DIR__ . "/../system/system.db_conn.php";
		}
		
		public function __destruct(){	//terminate database connection
			require __DIR__ . "/../system/system.db_close.php";
		}
	}

In my __construct() I have a require statement that loads the file with my database connection

	include_once __DIR__ . '/../settings/settings.system.database.php';

	// PDO Database Connection String //  // <== DONT CHANGE THIS VALUE
	switch(DB_SERVER_TYPE){
		case 1: //mySQL
			$db_connStr = 'mysql:host=' . DB_SERVER . ';dbname=' . DB_NAME;
			break;
		case 2: //MSSQL / MS Azure
			$db_connStr = 'sqlsrv:host=' . DB_SERVER . ';dbname=' . DB_NAME;
			break;
	}
	
	$pdoOptions = array( 
        //DONT CHANGE THESE VALUES
    	PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    	PDO::ATTR_EMULATE_PREPARES => FALSE);


	// DONT CHANGE THE FOLLOWING
	try{
		 $db_conn = new PDO($db_connStr, DB_USER, DB_PASS, $pdoOptions);

	}catch (PDOException $err){

		print 'Error: ' . $err->getMessage() . '<br/>';

		die();

	}

would I be able to call the $db_conn variable from other methods or is there something else I would need to do?

Guidance is appreciated.

You are off to a bad start. For starters the connection should be passed to the class by dependency injection.

There’s no point in writing code to close the database connection. PHP does it automatically

please explain dependency injection.

https://designpatternsphp.readthedocs.io/en/latest/Structural/DependencyInjection/README.html

Cmon, did you even try to google it before you posted?

1 Like

Try to invest some time to read about namespaces and autoloaders too if you can.

Sponsor our Newsletter | Privacy Policy | Terms of Service