0

I have three different classes which i use on a certain php page to extract some data from my database. Each class does it's own connect procedure using PDO. How can i check if a connection is already established to mysql using pdo ? My connection code is below:

try
{
    $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $DB_con->exec("SET CHARACTER SET utf8"); 
}
catch(PDOException $exception)
{
    echo $exception->getMessage();
}
  • 4
    ***Dependency injection!*** Don't "check", *know*. The way to know is that you only ever create one PDO instance, which you pass to each of your classes. – deceze Dec 16 '15 at 15:04
  • 1
    use Register Pattern or Singleton to make sure you are using only one connection! – Sebastian Brosch Dec 16 '15 at 15:21

1 Answers1

0

The solution would be to create a public $DB property (in each class) and then when you instantiate each class on your single page you pass the previous classes DB param to it like so:

class a {

    public $db = null

    public function setDB($db = null){
        if (is_null($db)){
            try
            {
                $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
                $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $DB_con->exec("SET CHARACTER SET utf8"); 
$this->db = $DB_con;
            }
            catch(PDOException $exception)
            {
                echo $exception->getMessage();
            }       
        } else {
            $this->db = $db;
        }
    }
}

class b and c would be the same as class a

Then on the page you load:

$a = new a;
$b = new b;
$b->setDB($a->db);
$c = new c;
$c->setDB($a->db);

You can then call your 3 classes but with only 1 database connection

Ukuser32
  • 2,147
  • 2
  • 22
  • 32