doumeng3188 2011-02-18 00:23
浏览 58
已采纳

PHP:将数据库层实现为单例可接受吗? 代码里面

I know singletons are bad. But is it bad for this, too?

class DaoMySQL {

    private static $instance;
    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);
}
  • 写回答

2条回答 默认 最新

  • doutang3760 2011-02-18 02:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测