geekcow / dbcore
PHP的基本、简单、轻量级ORM引擎
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-04 15:49:47 UTC
README
DBCore引擎使用文档
DBCore是一个为PHP应用程序设计的简单、轻量级的ORM(对象关系映射)引擎。它提供了一种使用PHP对象与数据库交互的简单方法,抽象了直接的数据库查询和操作。
入门指南
安装
要在项目中使用DBCore,您需要通过Composer安装它。在项目目录中运行以下命令
composer require geekcow/dbcore
确保您的项目已配置为自动加载Composer依赖项。这通常是通过将Composer生成的autoload.php
文件包含到您的项目中来完成的
require 'vendor/autoload.php';
配置
DBCore需要在项目目录中名为config.ini
的配置文件。此文件应包含您的数据库连接设置。一个示例配置可能看起来像这样
[database] host = "localhost" username = "your_username" password = "your_password" dbname = "your_database" port = 3306
请确保根据您的数据库服务器调整设置。
基本使用
定义实体
DBCore中的实体代表数据库中的表。要定义一个实体,扩展Entity
类并在类内定义您的表模式。例如
class User extends Entity { private $name_of_the_table = [ 'id' => ['type' => 'int', 'unique' => true, 'pk' => true], 'username' => ['type' => 'string', 'length' => 32, 'unique' => true], 'email' => ['type' => 'string', 'length' => 255] ]; public function __construct() { parent::__construct($this->name_of_the_table, get_class($this)); } }
执行数据库操作
一旦定义了实体,您可以执行各种数据库操作,如检索、插入、更新和删除。
检索数据
检索所有记录
$user = new User(); $result = $user->fetch();
通过ID检索特定记录
$user->fetch_id(['id' => '1']);
插入数据
插入新记录
$user = new User(); $user->columns['username'] = 'john_doe'; $user->columns['email'] = 'john@example.com'; $id = $user->insert();
更新数据
更新现有记录
$user->fetch_id(['id' => '1']); $user->columns['email'] = 'new_email@example.com'; $user->update();
删除数据
删除记录
$user->fetch_id(['id' => '1']); $user->delete();
高级使用
查询构建器
DBCore提供了一组查询构建器类,用于简化SQL查询的构建。这些构建器支持流畅的接口,允许您通过链式方法调用来逐步构建查询。
QuerySelectBuilder
使用QuerySelectBuilder
来构建SELECT查询。它支持选择列、指定条件、排序和限制结果。
示例用法
<?php // Step 1: Instantiate the QuerySelectBuilder class $selectBuilder = new QuerySelectBuilder(); // Step 2: Specify the table $selectBuilder->withTable('users'); // Step 3: Specify the columns $selectBuilder->withColumns(['id', 'username', 'email']); // Step 4: (Optional) For counting rows, uncomment the next line // $selectBuilder->forCount(true); // Step 5: Specify grouping criteria (if needed) // $selectBuilder->withGroup('department_id'); // Step 6: Add JOIN clause (if needed) // For demonstration, assuming we're not adding a JOIN clause here // Step 7: Generate the SQL query string $sqlQuery = $selectBuilder->toSql(); echo $sqlQuery;
QueryInsertBuilder
使用QueryInsertBuilder
来创建INSERT查询。它允许指定表和要插入的数据。
QueryUpdateBuilder
设计QueryUpdateBuilder
来构建UPDATE查询。它允许指定表、要更新的数据和条件。
QueryDeleteBuilder
QueryDeleteBuilder
便于创建DELETE查询。它支持指定表和删除条件。
这些构建器抽象了查询语法的复杂性,使您的代码更简洁,更容易维护。
有关更多高级功能和用法,请参阅DBCore引擎源代码中的特定方法和属性。该引擎设计为可扩展的,允许根据更复杂的应用程序需求进行自定义。
贡献
欢迎对DBCore做出贡献。要贡献
- 叉取仓库。
- 创建您的功能分支(
git checkout -b my-new-feature
)。 - 提交您的更改(
git commit -am 'Add some feature'
)。 - 推送到分支(
git push origin my-new-feature
)。 - 创建新的Pull Request。
您的贡献将帮助DBCore成为PHP社区更好的ORM引擎。