I know singletons are bad. But is it bad for this, too?
class DaoMySQL {
private static $instance开发者_如何学Go;
private $PDO;
private function __construct() {
$this->PDO = new PDO('mysql:dbname='.MYSQL_DEFAULT_DATABASE.';host='.MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD);
$this->PDO->query('SET NAMES \'utf8\'');
}
/**
* @return DaoMySQL
*/
static public function singleton() {
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c();
}
return self::$instance;
}
/**
* @return PDO
*/
public function getPDO() {
return $this->PDO;
}
}
To use this, I do something like this. (This is from my Bean class which all data objects extends.)
public function delete() {
$calledClassName = get_called_class();
$query = "DELETE FROM `" . $calledClassName::table . "` WHERE `id` = $this->id";
return DaoMySQL::singleton()->getPDO()->exec($query);
}
Many people are starting to use Dependency Injection containers to manage their objects instead of using singletons. Perhaps it's worth a look? Then all you need to ensure is that objects can access the container. You can fetch everything else from there.
Personally I use sfServiceContainer from Symfony Components. It's a stand-alone DI container and seems quite popular these days.
Update
You don't need to use a framework or a library. Fabien Potencier's articles on dependency injection should give you a good enough grasp of DI to implement your own. But why reinvent the wheel? Not using a good, existing library smells of NIH.
Note that there are many other DI libraries besides the sfServiceContainer that I use. Also note that sfServiceContainer is a completely stand-alone library. It does not need Symfony or any other framework. All it requires is plain old PHP.
The thing (well, one of them) that's wrong with Singletons is that the application should really be responsible for determining an object's life-cycle.
Have a read of Steve Yegge's article Singleton Considered Stupid
精彩评论