PHP - 数据库抽象层使用静态类与单例对象?

标签 php database oop static singleton

我不想讨论单例优于静态或优于全局等等。我在 SO 上阅读了很多关于类似主题的问题,但我无法对这个具体问题给出答案,所以我希望现在有人可以通过一个(或多个)真正简单的例子回答这个问题来启发我,而不仅仅是理论讨论。

在我的应用程序中,我有典型的 DB 类来抽象 DB 层并在 DB 上执行任务,而不必在代码中到处编写 mysql_connect/mysql_select_db/mysql...

我可以将类写成静态类:

class DB
{
   private static $connection = FALSE; //connection to be opened

   //DB connection values
   private static $server = NULL; private static $usr = NULL; private static $psw = NULL; private static $name = NULL;

   public static function init($db_server, $db_usr, $db_psw, $db_name)
   {
      //simply stores connections values, without opening connection
   }

   public static function query($query_string)
   {
      //performs query over alerady opened connection, if not open, it opens connection 1st
   }

   ...
}

或作为单例:

class DBSingleton
{
   private $inst = NULL;
   private $connection = FALSE; //connection to be opened

   //DB connection values
   private $server = NULL; private $usr = NULL; private $psw = NULL; private $name = NULL;

   public static function getInstance($db_server, $db_usr, $db_psw, $db_name)
   {
      //simply stores connections values, without opening connection

      if($inst === NULL)
         $this->inst = new DBSingleton();
      return $this->inst;
   }
   private __construct()...

   public function query($query_string)
   {
      //performs query over already opened connection, if connection is not open, it opens connection 1st
   }

   ...
}

然后在我的应用程序中,如果我想查询我可以做的数据库

//Performing query using static DB object
DB:init(HOST, USR, PSW, DB_NAME);
DB::query("SELECT...");

//Performing query using DB singleton
$temp = DBSingleton::getInstance(HOST, USR, PSW, DB_NAME);
$temp->query("SELECT...");

对我来说,Singleton 的唯一优势是避免将类的每个方法声明为 static。我相信你们中的一些人可以给我一个示例,说明单例在这个特定案例中的真正优势。提前致谢。

最佳答案

以下(简化的)示例有什么问题:

class Database
{
    protected $_connection;

    protected $_config;

    public function __construct( array $config ) // or other means of passing config vars
    {
        $this->_config = $config;
    }

    public function query( $query )
    {
        // use lazy loading getter
        return $this->_getConnection()->query( $query );
    }

    protected function _getConnection()
    {
        // lazy load connection
        if( $this->_connection === null )
        {
            $dsn = /* create valid dsn string from $this->_config */;

            try
            {
                $this->_connection = new PDO( $dsn, $this->_config[ 'username' ], $this->_config[ 'password' ] );
            }
            catch( PDOException $e )
            {
                /* handle failed connecting */
            }
        }

        return $this->_connection;
    }
}

$db1 = new Database( array(
    'driver'   => 'mysql',
    'host'     => 'localhost',
    'dbname'   => 'test',
    'username' => 'test_root',
    'password' => '**********'
) );

$db2 = new Database( array(
    'driver'   => 'pgsql',
    'host'     => '213.222.1.43',
    'dbname'   => 'otherdb',
    'username' => 'otherdb_root',
    'password' => '**********'
) );

$someModel       = new SomeModel( $db1 );
$someOtherModel  = new SomeOtherModel( $db2 );
$yetAnotherModel = new YetAnotherModel( $db2 );

这演示了如何使用延迟加载连接,并且仍然可以灵活地使用不同的数据库连接。

只有当使用其中一个实例(在本例中为模型之一)的对象决定调用实例的方法时,数据库实例才会连接到它们各自的连接。

关于PHP - 数据库抽象层使用静态类与单例对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2840912/

相关文章:

Javascript - getDomElement 链接到这里的哪里?

php - 排序函数是否考虑多级数组中的叶节点?

php - Nginx 在动态之前提供静态页面

php - 像谷歌一样的分页背后的逻辑

mysql - 按另一列分组的列的平均值

sql - 翻译 SPARQL-TO-SQL 查询

oop - 快速将单个文件类转换为文件夹类

php - 当今关于可扩展的高性能 PHP 应用程序的最佳方法

php - (x && y || z) 和 (x AND y OR z) 之间的区别

sql-server - 优势数据库或 SQL Server