user3047990
user3047990

Reputation: 31

Where I should store PDO connection?

I'm a bit confused: singletons are bad, globals worst. So what is the best practice to share an object, for example a PDO connection, between different classes?

I would like the same db connection being used by HTML template class, ACL class, and whatever.

I know the new trend is to use DI, but which is the best practice to make the same PDO connection global? Using a registry perhaps? Or by setting it as static var?

EDIT: What about this solution?

class Connection {

    protected static $instance;

    static function init(\PDO $connection) {
        if(isset(self::$instance ))
            throw new \Exception('A connection to a database has already been set.');

        self::$instance = $connection;
    }

    static function exec($query) {
        return self::$instance->exec($query);
    }
}

Connection::init(new PDO('blahblah'));

Connection::exec('SELECT * FROM users;');

Upvotes: 3

Views: 200

Answers (1)

Machavity
Machavity

Reputation: 31654

The best practice is to create your instance of PDO and then inject it into your class. This way you're not having to figure out in your class how to connect to your database.

class Something {
    /** @var \PDO */
    var $pdo;

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
    }
}

$class = new \Something($mypdo);

Upvotes: 1

Related Questions