3

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;');
  • 2
    I'd just say be pragmatic. Use a singleton or static registry if you want. It's not like you'll be [attacked by ferocious velociraptors](http://xkcd.com/292/) – Phil Nov 29 '13 at 04:34
  • There was some good discussion on the topic earlier this month [over here](http://stackoverflow.com/questions/19848384/php-pdo-instance-as-private-static-property). Might be worth your reading – Phil Nov 29 '13 at 04:39
  • thank you Phil, I just want to evolve :) I am going to drop singletons and since I am rewriting some code, I would like to do in the best way. – user3047990 Nov 29 '13 at 05:40

1 Answers1

1

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);
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • The issue (as always with these types of questions) is keeping that PDO instance in scope – Phil Nov 29 '13 at 04:35
  • this is a DI, I have some troubles using it in my application, I need a different solution or I need to rewrite it from scratch. – user3047990 Nov 29 '13 at 05:46