Установление подключения к базе данных в php с использованием одноэлементного класса

Может кто-нибудь, пожалуйста, назовите меня пример кода, чтобы установить соединение с базой данных в php, используя одноэлементный класс.

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(); 

Что-то вроде этого возможно? Очень простой, но должен дать вам отправную точку.

Вот как выглядит одноэлементный шаблон:

  <?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(); 

Теперь вы можете помещать в него случайные функции и параметры, которые обрабатывают ваш DB-материал. Надеюсь, это ответит на ваш вопрос.

См. Руководство для примера о том, как реализовать шаблон Singleton: http://www.php.net/manual/en/language.oop5.patterns.php

Затем просто установите соединение с базой данных в свой конструктор класса.

Я использую что-то вроде этого:

  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(); } } } 

Я использую что-то вроде ниже

 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);