View Single Post
Old 09-13-2012, 06:23 PM   PM User | #1
Oatley
New Coder

 
Join Date: Sep 2012
Posts: 70
Thanks: 56
Thanked 0 Times in 0 Posts
Oatley is an unknown quantity at this point
Connecting to a database through various classes

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::SERVERself::USERself::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
Oatley is offline   Reply With Quote