schonbeck/phpdatabase

此包已被放弃且不再维护。未建议替代包。

php的数据库连接器、适配器和配置器

2.0.4 2020-08-07 17:32 UTC

This package is auto-updated.

Last update: 2022-04-07 21:37:15 UTC


README

Latest Stable Version License

使用composer轻松安装

$ composer require schoenbeck/phpdatabase

函数

  • 与数据库建立连接
  • 向数据库发送请求
  • 检查和配置数据库和表

用法

创建连接

首先您需要加载数据库的连接配置。您需要声明以下部分

  • 主机
  • 端口
  • 驱动器
  • 用户
  • 密码
  • 数据库名

您可以选择两种方式来加载它们

  1. 将配置保存到$GLOBALS变量中
  2. 创建DatabaseConfig对象并将其传递给DatabaseConnection对象。

1. 将配置保存到$GLOBALS变量中

$GLOBALS变量的结构

$GLOBALS['GLOBAL_CONFIG']['DB']['host'] = "host";
$GLOBALS['GLOBAL_CONFIG']['DB']['port'] = "port";
$GLOBALS['GLOBAL_CONFIG']['DB']['driver'] = "driver";
$GLOBALS['GLOBAL_CONFIG']['DB']['user'] = "user";
$GLOBALS['GLOBAL_CONFIG']['DB']['password'] = "password";
$GLOBALS['GLOBAL_CONFIG']['DB']['database'] = "database";

创建一个新的DatabaseConnection对象,配置将被加载。

$databaseConnection = new DatabaseConnection($databaseConfiguration);

2. 创建DatabaseConfig对象

$databaseConfiguration = new DatabaseConfig('host', 'user', 'password', 'port', 'database', 'driver');
$databaseConnection = new DatabaseConnection($databaseConfiguration);

发送请求

您可以直接使用DatabaseConnection对象发送请求。

$query = 'SELECT * FROM User;';
$databaseConnection->execSQLStatement($query);

另一种发送请求到数据库的方式是使用DatabaseAdapter类,它会为您构建查询语句。

$databaseAdaptor = new DatabaseAdaptor($databaseConnection);
$result = $databaseAdaptor->selectFromTable('User', ['id', 'firstName', 'lastName']);

结果将自动格式化为php数组。

使用DatabaseConfigurator创建、修改或删除表和列

在您配置数据库之前,您必须创建一个配置文件。此文件包含表的配置。

注意,DatabaseConfigurator 始终为每个表添加一个索引。不要在配置文件中声明。

在当前版本的此包中,以下配置文件类型受到支持

  • Yaml
tables:
    User:
        firstName:
            type: varchar(50)
            default:
        lastName:
            type: int(10)
            default: -1
            notNull: true

创建配置文件后,您现在可以加载它们。为此,您创建一个DatabaseConfigurator对象并将其传递一个DatabaseAdaptor对象。

$databaseConfigurator = new DatabaseConfigurator($databaseAdaptor);

对于每种支持的配置文件类型都存在一个自己的方法来加载和配置数据库。

$databaseConfigurator->checkDatabaseConfigYamlFile('database.yml')

DryRun

DatabaseConfigurator支持'dryRun'模式。它返回一个包含配置器将要发送的查询的数组。

$databaseConfigurator->checkDatabaseConfigYamlFile('database.yml', $dryRun = true)

许可

MIT 许可证,https://open-source.org.cn/licenses/MIT