duandou8120 2019-03-16 20:43
浏览 93

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

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:

  1. I don't want to wrap 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

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());
}
  • 写回答

1条回答 默认 最新

  • dongwu9063 2019-03-16 22:17
    关注

    If you want complete control over opening and closing connections then I suggest we only centralise the $dsn, $user, $pass and $options variables. I'm assuming there are also variables like $host, $db and $charset which you did not reveal to us but lets add them.

    Lets call this file 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.

    Lets call this page 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!

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100