太多数据库连接php [英] Too many database connection php
问题描述
在我的 logout.php
端点中,我使用3个不同的类.这3个课程中的每一个都具有:
In my logout.php
endpoint I'm using 3 different classes. Each of this 3 classes have:
private $conn;
private $table_name = "users";
// constructor with $db as database connection
public function __construct($db)
{
$this->conn = $db;
}
此代码是为了在初始化类时从端点连接到数据库,如下所示:
this code in order to connect to database from endpoint while initializing class like so:
// include needed files
include_once '../config/database.php';
include_once '../classes/user.php';
include_once '../classes/token.php';
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
// initialize object
$user = new user($db);
$token = new token($db);
在这3个类的某些函数中,有时我需要使用其他类,因此我还包括了数据库类再次类似于 user 类中的此注销功能:
In this 3 classes in some functions I sometimes need to use other class so I additionally include database class once again like in this logout function within user class:
public function logout($receivedToken)
{
include_once '../config/database.php';
include_once '../classes/token.php';
// instantiate database
$database = new Database();
$db = $database->getConnection();
$token = new token($db);
if($token->checkToken($receivedToken))
而且我不确定这是否正确,我正在调试代码并尝试对其进行重构以使其更有意义.为了使用令牌类,是否需要在用户类的注销功能中再次包含该数据库?还是我可以以某种方式使用我通过 __ construct
在端点中初始化的连接,而不是一次又一次地 include
数据库初始化该连接?
And I'm not sure if it is correct approach I'm debugging my code and trying to refactor it to make more sense. Do I need to include this db once again there in logout function within user class in order to use token class? Or maybe I can somehow use this connection which I did initialize in endpoint via __construct
and not include
database over and over again?
推荐答案
这是一个不好的方法,首先,您应该只在文件顶部一次 include
.
This is a bad approach, first of all, you should only include
once at the top of your file.
无需在注销方法中再次包含它,并且在我看来,方法主体内部的 includes
通常是一种代码味道,除非在某些特定情况下.
There is no need to include it again in the logout method and generally includes
inside of method bodies are usually a code smell in my opinion, except in some specific cases.
第二,每次实例化数据库类 $ database = new Database()
并调用 $ database-> getConnection()时,您都将与数据库建立两个连接.代码>,您正在与数据库建立新连接.您只应实例化一次Database,然后将其注入需要DB连接的类(通过构造函数或方法参数传递它).
Secondly you are making two many connections to your database, every time you instantiate the Database class $database = new Database()
and call $database->getConnection()
you are making a new connection to the database. You should only instantiate Database once, and then inject it into classes that need DB connection (pass it through constructor or as a method param).
最后但并非最不重要的一点,您应确保您的 $ database-> getConnection()
返回单个.
Last but not the least, you should ensure that your $database->getConnection()
returns a singleton.
您可以这样做
<?php
class Database
{
// specify your own database credentials
private $host = "localhost";
private $db_name = "obiezaca_db";
private $username = "root";
private $password = "";
private $conn;
// get the database connection
public function getConnection()
{
if (!$this->conn) {
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->exec("set names utf8");
} catch(PDOException $exception) {
// you shouldn't output exception error message in production
// because it can leak sensitive data such as DB username and password
echo "Database error";
}
}
return $this->conn;
}
}
?>
或者您可以像这样建立Singletton工厂
Or you could make a Singletton factory like this
<?php
class Database
{
// specify your own database credentials
private $host = "localhost";
private $db_name = "obiezaca_db";
private $username = "root";
private $password = "";
private $conn;
private static $instance;
private function __construct() {};
private function __clone() {};
public static getInstance()
{
if (!static::$instance) {
static::$instance = new Database();
}
return static::$instance;
}
// get the database connection
public function getConnection()
{
if (!$this->conn) {
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->exec("set names utf8");
} catch(PDOException $exception) {
// you shouldn't output exception error message in production
// because it can leak sensitive data such as DB username and password
echo "Database error";
}
}
return $this->conn;
}
}
$database = Database::getInstance();
$connection = $database->getConnection();
采用这种方法,无论您在代码中调用这些方法多少次,都将始终获得相同的 Database
和 PDO
对象实例.
In this approach no matter how many times in your code you call these methods you will always get the same Database
and PDO
object instances.
这样,您将确保自己始终与数据库建立一个连接,此外,由于数据库是静态访问的,因此可以全局访问.
This way you will ensure that you always have one connection to your database, and additionally your database will be globally accessible since it is accessed statically.
这篇关于太多数据库连接php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!