首页 > 解决方案 > 在多个 PHP 脚本中使用数据库类

问题描述

我使用 DB 类(带有 PDO)来访问 MySQL 服务器,我在这方面有一个问题。

我有一个看起来像这样的项目结构: 项目结构

我的问题是我需要在每个脚本中创建和关闭 DB 对象或有其他解决方案来解决这个问题?在这些情况下的习惯是什么?我可以以某种方式概括下面的代码片段吗?

现在在受影响的页面中看起来像这样:

try
{
    $db = new DB();
} catch (DBException $e)
{
    forwardToErrorPage($e->getMessage());
    return;
}

try
{
    if ($db->someDBFunction($args) == 0)
        header("Location: ../templates/success.php");
    else
        forwardToErrorPage('Adding person failed');
} catch (DBException $e)
{
    forwardToErrorPage($e->getMessage());
}
finally
{
    $db->close();
}

标签: phpdatabaseoopobjecttry-catch

解决方案


您可以包含require_once('/path/to/project/src/DB.php');在所有文件的标题中,并在 DB.php 中制作您的数据库句柄:

try
{
    $db = new DB();
} catch (DBException $e)
{
    forwardToErrorPage($e->getMessage());
    return;
}

更好的解决方案,我建议使用像 Eloquent (参考)这样的 ORM:

composer require illuminate/database

然后在您的 DB.php 文件中:

require_once "vendor/autoload.php";
use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection([
   "driver" => "mysql",
   "host" =>"127.0.0.1",
   "database" => "acl",
   "username" => "root",
   "password" => ""
]);

$capsule->setAsGlobal();
$capsule->bootEloquent();

推荐阅读