The correct way to connect PDO for classes

Is it right to do PDO Connection.

I have different classes (each class has its own file), then there is a configuration file containing a PDO object and all class objects. Am I doing it right or is there a best practice.

classA.php

class classA {

    private $PDO;

    function __construct($PDO) { 
        $this->PDO = $PDO;
    }
    //other functions
}

classB.php

class classB {

    private $PDO;

    function __construct($PDO) { 
        $this->PDO = $PDO;
    }
    //other functions
}

classC.php

class classC {

    private $PDO;

    function __construct($PDO) { 
        $this->PDO = $PDO;
    }
    //other functions
}

And on the config.php page:

include_once("db.php"); //contains db variables values
try
{
    $PDO = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
    die("Failed to connect database: " . $ex->getMessage());
}

require 'classA.php';
require 'classB.php';
require 'classC.php';

$objA = new classA($PDO);
$objB = new classB($PDO);
$objC = new classC($PDO);

include config.php on almost every page.

+4
source share
2 answers

Short: yes, that's right, but not perfect.

I think you are doing everything right. It was called Injection of Dependencies .

But your code has duplicates ( DRY! ). You can avoid this using inheritance.

. , "".

config.php .

, . .

+2

. ( )

, .

, Singleton, :

" , Singleton, "

0

All Articles