简体   繁体   English

如何在多个类中使用PDO连接到数据库?

[英]How to connect to database using PDO in multiple classes?

I have multiple classes and most of them need to connect to database, 我有多个类,大多数都需要连接到数据库,

How can I set PDO options/host/dbname etc only once and then use it in every class while having the following in mind: 如何设置PDO选项/主机/数据库等只一次,然后在每个类中使用它,同时牢记以下内容:

  1. I don't want to wrap PDO 我不想包装PDO
  2. I need to close the PDO connection after each query ( $db=null ), so I simply cannot just use $db = new PDO(...) and then pass $db to my classes 我需要在每次查询后关闭PDO连接( $db=null ),所以我不能只使用$db = new PDO(...)然后将$db传递给我的类

I want to skip having this in every class that needs to connect to the database: 我想跳过每个需要连接数据库的类中的内容:

<?php

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

If you want complete control over opening and closing connections then I suggest we only centralise the $dsn , $user , $pass and $options variables. 如果你想完全控制打开和关闭连接,那么我建议我们只集中$dsn$user$pass$options变量。 I'm assuming there are also variables like $host , $db and $charset which you did not reveal to us but lets add them. 我假设还有像$host$db$charset这样的变量,你没有透露给我们,但我们可以添加它们。

Lets call this file global_db.php : 让我们将此文件称为global_db.php

<?php
$host = "127.0.0.1";
$db = "mydb";
$charset = "UTF-8";
$user = "root";
$pass = "";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

That looks like we have all the goods there, keep in mind I am not testing this so we might get a syntax error or two. 看起来我们在那里有所有商品,请记住我没有测试这个,所以我们可能会得到一两个语法错误。

Now in our classes or other php files where we want to open a connection. 现在在我们的类或其他我们想要打开连接的php文件中。

Lets call this page fooClass.php 让我们把这个页面fooClass.php

<?php
require_once 'global_db.php';

class FooClass {
    public function __construct() {
        try {
            $pdo = new PDO(
                    $GLOBALS['dsn'],
                    $GLOBALS['user'],
                    $GLOBALS['pass'],
                    $GLOBALS['options']);
        } catch (\PDOException $e) {
            throw new \PDOException($e->getMessage(), (int)$e->getCode());
        }
    }
}

That should do the trick or at least give you a general idea on where to go from here on your own route. 这应该是诀窍,或者至少可以让你大致了解从你自己的路线到这里的路线。 There are many other ways to accomplish similar but no need to overcomplicate things. 还有许多其他方法可以实现类似但不需要过于复杂的事情。

nJoy! 的nJoy!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM