douliaodun9153 2013-01-27 20:07
浏览 67
已采纳

PDO:连接为singleton =线程问题?

So I finally started to refactor the base of my PHP office app: I added new functionality to it based on a singleton PDO-class, which I was planning to deploy throughout the whole app. It is very straightforward and working (for now) as it should:

class DB {

    protected static $instance;
    protected function __construct() {}
    public static function getInstance()
    {

        if( empty( self::$instance ) )
        {
            $dsn =  'pgsql:host=' . Config::$a .
                    ';dbname='    . Config::$b .
                    ';port='      . Config::$c .
                    ';connect_timeout=15';            
            $db_user = Config::$d;             
            $db_pass = Config::$e;

            try
            {
                self::$instance = new PDO( $dsn, $db_user, $db_pass );
                self::$instance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            }  
            catch( PDOException $e )
            {  
                new Log( 6, "DB Class failed to connect to dbase: $e" );
            }                          
        }
        return self::$instance;
    }
}

This afternoon I'm telling a friend of mine, who is a .NET-programmer about this singleton db-connection class, and he warns me that using a singleton to connect to a database can lead to threading-problems.

I must say that it had crossed my mind: several users will be using the app, and almost all functionality is related to (multiple) db-queries. It is not unthinkable that two users will be executing a query at the same time.

Is PDO (or PHP, or Apache (at the office), or Nginx (testing environment at home)) capable of dealing with this? Maybe a new instance is given for every user? Maybe I should use this singleton together with transactions that will lock the database for every query/update/insert/delete to avoid threading problems? Or maybe my friend is wrong and I don't have to worry?

Thx for any insights!

  • 写回答

2条回答 默认 最新

  • dsfds2343 2013-01-27 20:11
    关注

    Do not worry about using a singleton to establish the connection.

    Every php script request will have its own thread. I mean, if two simultaneous requests happen, the web server will execute your singleton in two different threads, so you finally will have two different objects dealing with the database connection.

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

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据