Hello,
I'm wondering about the best practice involved for connecting to a database throughout several other classes in OOP.
I have a connection class, which I have created as a singleton pattern like so
PHP Code:
class Connection {
const SERVER = "xxxxxxxxxxxxxxxxxxxxxx";
const USER = "xxxxxxxxxxxxxxxxxxxxxx";
const PASSWORD = "xxxxxxxxxxxxxxxxxxxxxx";
const DBNAME = "xxxxxxxxxxxxxxxxxxxxxx";
/**
* Store a single instance of the database
* */
private static $instance;
/**
* Getter method for returning a single instance of the class
**/
public static function getConnection() {
if(!isset(self::$instance)) {
$CONN = mysql_connect(self::SERVER, self::USER, self::PASSWORD) or die ('Unable to select database: '.mysql_error ());
$DB = mysql_select_db(self::DBNAME,$CONN);
}
return self::$instance;
}
}
PHP Code:
//Connect to database
$connection = Connection::getConnection();
Now all of my classes on my site will need database access to run various queries, so what is best practice here?
For each of these classes to extend the connection class or is there a better way? Maybe passing in some connection object to each of these classes?
Can anyone please help me to show how I can use my singleton connection class within in another class that runs a query to the database? An example would be great if that's not too much to ask for.
Thank you for reading this