php - 在多个 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();
}
解决方案
您可以包含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();
推荐阅读
- python - AttributeError:“网站”对象在 odoo 13 中没有属性“get_active_website_setting”
- javascript - 使用 moment.js 解析和显示 Laravel updated_at 时间戳
- javascript - 给 textarea 的分词不会被添加到通过 react-to-pdf 包生成的 pdf 中
- node.js - 无法打开赛普拉斯
- c# - C# OxyPlot:如何在图表上显示点值?
- react-native - 在 React Native 中使用 Expo 的一个信号推送通知
- python - 基本上只使用带有单个整数值的括号从数组列表中删除重复项
- rollup - 更改 rollup-plugin-postcss 为某些文件生成的 CSS 类名
- javascript - 在我的情况下,如何解决“超出最大更新深度”?
- pandas - 如何在连接两个单独的数据帧时在熊猫数据帧中保留多索引