我通过PDO访问我的MySQL数据库.我正在设置对数据库的访问权限,我的第一次尝试是使用以下内容:
我想到的第一件事是global:
$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd');
function some_function() {
global $db;
$db->query('...');
}
Run Code Online (Sandbox Code Playgroud)
这被认为是一种不好的做法.一点点搜索后,我结束了与Singleton模式,其
"适用于需要单个类实例的情况."
根据手册中的示例,我们应该这样做:
class Database {
private static $instance, $db;
private function __construct(){}
static function singleton() {
if(!isset(self::$instance))
self::$instance = new __CLASS__;
return self:$instance;
}
function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd')
return self::$db;
}
}
function some_function() {
$db = Database::singleton();
$db->get()->query('...');
}
some_function();
Run Code Online (Sandbox Code Playgroud)
当我能做到这一点时,为什么我需要相对较大的课程呢?
class Database {
private static $db;
private function __construct(){}
static function get() …Run Code Online (Sandbox Code Playgroud) 在PHP中使用单例而不是全局的数据库连接有什么好处?我觉得使用单例而不是全局会使代码变得不必要地复杂化.
$conn = new PDO(...);
function getSomething()
{
global $conn;
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
class DB_Instance
{
private static $db;
public static function getDBO()
{
if (!self::$db)
self::$db = new PDO(...);
return self::$db;
}
}
function getSomething()
{
$conn = DB_Instance::getDBO();
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
如果有一种更好的方法来初始化除全局或单例之外的数据库连接,请提及它并描述它相对于全局或单例的优势.
让我先介绍一下.我正在学习PHP中的OOP.我也研究过设计模式,但还没有完全掌握不同类型的概念.我正处于这样的阶段,每隔几个月我就会意识到我没有按照正确的方式做事并且必须改变我的风格.这太令人沮丧了.因此,我想找出一劳永逸的正确做事方式.我试图在Stackoverflow上完整阅读以下主题:
ORM
数据映射器
Singleton
Globals是邪恶的
一切相关
但是我仍然不清楚一些事情.我在这里发布我的代码在一个清晰,简明的方式,并希望人们能指出双方的良好做法和坏的.我会在最后列出我的所有问题.
请不要关闭作为重复,我诚实地搜索了关于该主题的几乎所有问题,但我仍然想知道一些我无法澄清的事情.对不起,它已经很久了,但我试图整理它,所以它应该读得很好!
我将首先发布我的数据库类的基本知识.
为database.php
<?php
class DatabaseMySQL{
private static $dbh;
public function __construct(){
$this->open_connection();
}
public function open_connection(){
if(!self::$dbh){
return (self::$dbh = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER,DB_PASSWORD)) ? true : false;
}
return true;
}
public function query($sql, $params=array()){
$this->last_query = $sql;
$stmt = self::$dbh->prepare($sql);
$result = $stmt->execute($params);
return $result ? $stmt : $stmt->errorInfo();
}
public function fetch_all($results, $class_name=''){
return $results->fetchAll(PDO::FETCH_CLASS, $class_name);
}
}
?>
Run Code Online (Sandbox Code Playgroud)
这是我的数据库类文件.这个类允许我创建我喜欢这个类的任意数量的实例,它将重用已经实例化的PDO对象作为类的静态属性存储.它还使用PDO从结果集中获取数据,以将数据作为指定类的对象获取.
我的下一个文件是我所有其他类继承的类.我称之为MainModel.我不知道这是否符合惯例.
MainModel.php
<?php
abstract class MainModel{ …Run Code Online (Sandbox Code Playgroud) <?php
require_once('app/config.php'); // Require constants HOST, DATABASE, USER, PASSWORD
/*
dbConnection class.
Manages connections to and operations on the database. Call dbConnection::getInstance() to return an instance.
Prepare your statements by calling prepareQuery() on the object
Attribute list:
$instance:
> Static self instance to manage database resource
$connection:
> Holds connection resource
$sth:
> Statement handler variable. Handles SQL statements.
_______________________________________________________________________________________________________________
Method list:
getInstance():
> Creates or returns existing connection to the database
prepareQuery():
> Prepares the $sth …Run Code Online (Sandbox Code Playgroud)