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;');