在php中使用单例类建立数据库连接

发布于 2024-11-27 02:53:39 字数 42 浏览 0 评论 0原文

任何人都可以指导我使用示例代码在 php 中使用单例类建立数据库连接。

Can anybody please guide me with a sample code to establish a database connection in php using singleton class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

风吹过旳痕迹 2024-12-04 02:53:39
class DatabaseSingleton
{
  // [Singleton]
  private static $instance = null;
  public static function getInstance()
  {
    if (!self::$instance)
    {
      self::$instance = new self();
    }
    return self::$instance;
  }
  private function __clone(){}
  // [/Singleton]

  private $connection = null;

  private function __construct()
  {
    $this->connection = mysql_connect('localhost','root','admin');
    if ($this->connection)
    {
      mysql_select_db('my_database');
    }
  }

  //
  // crud operations go here.
  //
}

$db = DatabaseSingleton::getInstance();
$db->SomeCRUDOperation();

也许是这样的?非常基础,但应该为您提供一个起点。

class DatabaseSingleton
{
  // [Singleton]
  private static $instance = null;
  public static function getInstance()
  {
    if (!self::$instance)
    {
      self::$instance = new self();
    }
    return self::$instance;
  }
  private function __clone(){}
  // [/Singleton]

  private $connection = null;

  private function __construct()
  {
    $this->connection = mysql_connect('localhost','root','admin');
    if ($this->connection)
    {
      mysql_select_db('my_database');
    }
  }

  //
  // crud operations go here.
  //
}

$db = DatabaseSingleton::getInstance();
$db->SomeCRUDOperation();

Something like that perhaps? Very basic, but should give you a starting point.

很酷不放纵 2024-12-04 02:53:39

这就是单例模式的样子:

 <?php
 class SingletonClass
 {
     static private $instance = null;

 static public function getInstance()
 {
     if (null === self::$instance) {
         self::$instance = new self;
     }
     return self::$instance;
 }

 private function __construct(){}
 private function __clone(){}


}

$singletonClass = SingletonClass::getInstance();

现在您可以在其中放置随机函数和参数来处理您的数据库内容。我希望这能回答你的问题。

That's how a singleton-pattern looks like:

 <?php
 class SingletonClass
 {
     static private $instance = null;

 static public function getInstance()
 {
     if (null === self::$instance) {
         self::$instance = new self;
     }
     return self::$instance;
 }

 private function __construct(){}
 private function __clone(){}


}

$singletonClass = SingletonClass::getInstance();

Now you can put random functions and parameters in there that handle your DB-stuff. I hope that answers your question.

萌逼全场 2024-12-04 02:53:39

有关如何实现单例模式的示例,请参阅手册: http:// /www.php.net/manual/en/language.oop5.patterns.php

然后只需在类构造函数中建立数据库连接即可。

See the manual for an example on how to implement the Singleton pattern: http://www.php.net/manual/en/language.oop5.patterns.php

Then just establish the database connection in your class constructor.

凉城凉梦凉人心 2024-12-04 02:53:39

我用这样的东西:

  class DBConn
    {
        static private $_db = null; // The same PDO will persist from one call to the next
        private function __construct() {} // disallow calling the class via new DBConn
        private function __clone() {} // disallow cloning the class
        /**
         * Establishes a PDO connection if one doesn't exist,
         * or simply returns the already existing connection.
         * @return PDO A working PDO connection
         */
        static public function getConnection()
        {
            if (self::$_db == null) { // No PDO exists yet, so make one and send it back.
                try {
                    self::$_db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
                } catch (PDOException $e) {
                    // Use next line for debugging only, remove or comment out before going live.
                    // echo 'PDO says: ' . $e->getMessage() . '<br />';
                    // This is all the end user should see if the connection fails.
                    die('<h1>Sorry. The Database connection is temporarily unavailable.</h1>');
                } // end PDO connection try/catch
                return self::$_db;
            } else { // There is already a PDO, so just send it back.
                return self::$_db;
            } // end PDO exists if/else
        } // end function getConnection
    } // end class DBConn


    /**
     * And you can use it as such in a class
     * */

     class Post {
        public function __construct(){
             $this->db = DBConn::getConnection();
        }
        public function getPosts()
        {
            try {
                /*** The SQL SELECT statement ***/
                $sql = "SELECT * FROM posts";
                foreach ($this->_dbh->query($sql) as $row) {
                    var_dump($row);
                }
                /*** close the database connection ***/
                $this->_dbh = null;
            } catch (PDOException $e) {
                echo $e->getMessage();
            }
        }
    }

I use something like this:

  class DBConn
    {
        static private $_db = null; // The same PDO will persist from one call to the next
        private function __construct() {} // disallow calling the class via new DBConn
        private function __clone() {} // disallow cloning the class
        /**
         * Establishes a PDO connection if one doesn't exist,
         * or simply returns the already existing connection.
         * @return PDO A working PDO connection
         */
        static public function getConnection()
        {
            if (self::$_db == null) { // No PDO exists yet, so make one and send it back.
                try {
                    self::$_db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
                } catch (PDOException $e) {
                    // Use next line for debugging only, remove or comment out before going live.
                    // echo 'PDO says: ' . $e->getMessage() . '<br />';
                    // This is all the end user should see if the connection fails.
                    die('<h1>Sorry. The Database connection is temporarily unavailable.</h1>');
                } // end PDO connection try/catch
                return self::$_db;
            } else { // There is already a PDO, so just send it back.
                return self::$_db;
            } // end PDO exists if/else
        } // end function getConnection
    } // end class DBConn


    /**
     * And you can use it as such in a class
     * */

     class Post {
        public function __construct(){
             $this->db = DBConn::getConnection();
        }
        public function getPosts()
        {
            try {
                /*** The SQL SELECT statement ***/
                $sql = "SELECT * FROM posts";
                foreach ($this->_dbh->query($sql) as $row) {
                    var_dump($row);
                }
                /*** close the database connection ***/
                $this->_dbh = null;
            } catch (PDOException $e) {
                echo $e->getMessage();
            }
        }
    }
天涯离梦残月幽梦 2024-12-04 02:53:39

我正在使用类似下面的东西

class Database 

{   

 private $_connection;

    private static $_instance; //The single instance

    private $_host = "HOST";

    private $_username = "USERNAME";
    private $_password = "PASSWORd";
    private $_database = "DATABASE";


    public static function getInstance() {
        if(!self::$_instance) { // If no instance then make one
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        $this->_connection = new mysqli($this->_host, $this->_username, 
            $this->_password, $this->_database);

        // Error handling
        if(mysqli_connect_error()) {
            trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error(),
                 E_USER_ERROR);
        }
    }

    // Magic method clone is for prevent duplication of connection
    private function __clone() { }

    public function getConnection() {
        return $this->_connection;
    }

}


$db = Database::getInstance();

$mysqli = $db->getConnection();

$sql_query = "SELECT foo FROM  etc";

$result = $mysqli->query($sql_query);

I am using something like below

class Database 

{   

 private $_connection;

    private static $_instance; //The single instance

    private $_host = "HOST";

    private $_username = "USERNAME";
    private $_password = "PASSWORd";
    private $_database = "DATABASE";


    public static function getInstance() {
        if(!self::$_instance) { // If no instance then make one
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        $this->_connection = new mysqli($this->_host, $this->_username, 
            $this->_password, $this->_database);

        // Error handling
        if(mysqli_connect_error()) {
            trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error(),
                 E_USER_ERROR);
        }
    }

    // Magic method clone is for prevent duplication of connection
    private function __clone() { }

    public function getConnection() {
        return $this->_connection;
    }

}


$db = Database::getInstance();

$mysqli = $db->getConnection();

$sql_query = "SELECT foo FROM  etc";

$result = $mysqli->query($sql_query);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文