Vpp Man
Vpp Man

Reputation: 2546

Passing same PDO object to different classes

I have classes like this:

classPages.php

class pages {

    private $dbh;

    function __construct($dbh) { 
        $this->dbh = $dbh;
    }
    //...
}

classNews.php

class news {

    private $dbh;

    function __construct($dbh) { 
        $this->dbh = $dbh;
    }
    //...
}

classMod.php

class mod {

    private $dbh;

    function __construct($dbh) { 
        $this->dbh = $dbh;
    }
    //...
}

And in index page:

try
{
    $dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
    die("Failed to connect to the database: " . $ex->getMessage());
}

require 'classPages.php';
require 'classNews.php';
require 'classMod.php';

$pages = new pages($dbh);
$news = new news($dbh);
$mod = new mod($dbh);

//use above objects where needed

So i create single PDO object. Then pass it to the constructors of each classes. Then i use these objects and calls it's member functions which does fetching and insertion of data using this pdo object passed to constructor.

Is it correct way? Or any conflicts directly/indirectly happen?

Upvotes: 2

Views: 1404

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

This is the correct way. You don't create a different DB connection each time, which is optimal (not sure that new PDO instances do that anyway, but you can at least be sure).

When you prepare statements in PDO, it creates a separate instance so there is no worry of conflict there. The only possible problem is if you change some of the attributes of the PDO instance in one class and depend on working with different attributes in another (but this is highly unlikely).

One of the goals of Object Oriented Programming is to reuse resources which is exactly what this does.

Upvotes: 1

Related Questions