php 单例数据库连接,这段代码是不好的做法吗?

发布于 2025-01-04 11:54:27 字数 1438 浏览 3 评论 0原文

我正在尝试创建一个简单易用的单例类来连接到 mysql 数据库并执行查询,代码工作正常并且我没有遇到任何问题,但由于我是 OOP 新手,我想知道这是否是否是不好的做法。

这是该类

class Database {
private $databaseName = 'dbname';
private $host = 'localhost';
private $user = 'user';
private $password = 'pass'; 
private static $instance; //store the single instance of the database

private function __construct(){
    //This will load only once regardless of how many times the class is called
    $connection = mysql_connect($this->host, $this->user, $this->password) or die (mysql_error());
    $db = mysql_select_db($this->databaseName, $connection) or die(mysql_error()); 
    echo 'DB initiated<br>';
}

//this function makes sure there's only 1 instance of the Database class
public static function getInstance(){
    if(!self::$instance){
        self::$instance = new Database();
    }
    return self::$instance;     
}

public function connect() { 
    //db connection
} 
public function query($query) {
    //queries   
    $sql = mysql_query($query) or die(mysql_error()); 
    return $sql;
}

public function numrows($query) {
    //count number of rows  
    $sql = $this->query($query);
    return mysql_num_rows($sql);
}


}

//Intantiate the class
$database = Database::getInstance();

,当我想使用该类时,我会这样做:

$query = "SELECT * FROM registrations";
echo $database->numrows($query);
$sql = $database->query($query);

I'm trying to create a simple to use singleton class to connect to mysql database and do queries, the code works fine and i haven't had any problems with it, but since I'm new to OOP I'm wondering whether this is bad practice or not.

Here's the class

class Database {
private $databaseName = 'dbname';
private $host = 'localhost';
private $user = 'user';
private $password = 'pass'; 
private static $instance; //store the single instance of the database

private function __construct(){
    //This will load only once regardless of how many times the class is called
    $connection = mysql_connect($this->host, $this->user, $this->password) or die (mysql_error());
    $db = mysql_select_db($this->databaseName, $connection) or die(mysql_error()); 
    echo 'DB initiated<br>';
}

//this function makes sure there's only 1 instance of the Database class
public static function getInstance(){
    if(!self::$instance){
        self::$instance = new Database();
    }
    return self::$instance;     
}

public function connect() { 
    //db connection
} 
public function query($query) {
    //queries   
    $sql = mysql_query($query) or die(mysql_error()); 
    return $sql;
}

public function numrows($query) {
    //count number of rows  
    $sql = $this->query($query);
    return mysql_num_rows($sql);
}


}

//Intantiate the class
$database = Database::getInstance();

and when i want to use the class I would do:

$query = "SELECT * FROM registrations";
echo $database->numrows($query);
$sql = $database->query($query);

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

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

发布评论

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

评论(4

绅刃 2025-01-11 11:54:27

单身人士是个坏消息。

  • 他们将全局状态引入程序中。大多数程序员应该熟悉为什么全局状态不好。
  • 它们在单例和使用它的任何类之间引入了紧密耦合。这意味着如果不重用单例,就无法重用相关类。
  • 他们对依赖于单例的类进行单元测试是有问题的,因为您无法轻松地用模拟替换单例。
  • 他们鼓励类尝试解决自己的依赖关系的编码风格。这很糟糕,因为它会降低类具有哪些依赖项的清晰度。
  • PHP 具有一种无共享架构,这意味着 PHP 单例根本不是真正的单例,任何时候都可以有多个活动实例(每个打开请求一个实例)。
  • 如果稍后您突然发现您实际上需要单例提供的多个资源,会发生什么情况?这是比您想象的更常见的情况

您最好查看 ,因为它解决了上述问题。

Singletons are bad news.

  • They introduce global state into a program. Most programmers should be familiar with why global state is bad.
  • They introduce tight coupling between the singleton and any class that uses it. This means you can't reuse the classes in question without reusing the singleton too.
  • They make unit testing of classes that depend on the singleton problematic because you can't easily replace the singleton with a mock.
  • They encourage a coding style where classes attempt to resolve their own dependencies. This is bad because it can reduce clarity regarding what dependencies the class has.
  • PHP has a Share Nothing Architecture, meaning that PHP singletons aren't really singletons at all, there can be multiple instances alive at any one time (one per open request).
  • What happens if you suddenly discover at some later date that you actually need more than one of the resource that's being provided by the singleton? It's a more common scenario than you might think

You're better off looking at instead, as it resolves the above issues.

<逆流佳人身旁 2025-01-11 11:54:27

我认为单例对于连接管理器来说是可以的,但对于连接本身来说就不行了。

您永远不知道何时需要为开发的特定部分建立额外的连接。假设您突然需要添加与远程数据库的同步。

连接管理器(可以管理多个连接)可以是单例。连接本身;不。

您的连接管理器还应该能够加载“驱动程序”,以便您能够实例化 MySQL 连接,并且当您需要 msSQL、sqlite 或其他任何东西时,您可以添加所需的驱动程序。

I think a singleton can be OK for a connection manager, but not for a connexion itself.

You never know when you'll need to have an extra connection for a specific part of your development. Let say you suddently need to add a synchronisation with a remote database.

A connection manager (who can manage multiple connection) can be a singleton. A connection itself; no.

You connection manager should also be able to load "Drivers", so that you'll be able to instanciate a MySQL connection and the day you need msSQL, sqLite or anything else, you're able to add the needed drivers.

ヤ经典坏疍 2025-01-11 11:54:27

这种模式很好,因为单例仅适用于当前用户会话。这个决定实际上取决于您的优先事项。如果您希望为用户提供更快的性能,那么您希望每个用户允许更多的数据库连接,但如果您想限制数据库受到攻击的程度,那么单例为您提供了一个很好的中间道路。

This pattern will be fine because the singleton will only apply to the current user session. The decision really comes down to what your priority is. If you want faster performance for the user then you want to allow more database connections per user, but if you want to limit how hard your database gets hit then the singleton gives you a good middle of the road.

稚然 2025-01-11 11:54:27

我听到的关于 PHP 中 Singleton 设计模式的唯一积极的论点来自一位开发人员,他结合 Memcached 对象实现了 Singleton 数据库连接。我实际上没有机会查看代码和性能,但他能够提出连贯的论点。

就我个人而言,我不认为单例设计模式与 PHP 非常相关,无论如何 PHP 基本上都是无状态的(正如之前指出的,每个请求都会有一个单例)。

The only positive argument I've heard for the Singleton design pattern in PHP was from a developer who implemented a Singleton database connection in conjunction with a Memcached object. I didn't actually get a chance to look at the code and performance but he was able to put forward a coherent argument.

Personally I don't believe that the Singleton design pattern is very relevant to PHP, which is largely stateless anyway (as pointed out before each request will have a singleton).

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