initorm/database

InitORM 数据库管理器

1.0.1 2023-12-15 11:36 UTC

This package is not auto-updated.

Last update: 2024-09-20 14:56:12 UTC


README

使用或无需抽象管理您的数据库。这个库基于PHP PDO插件构建,主要用于构建和执行SQL查询。

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

要求

  • PHP 8.0及以上版本。
  • PHP PDO扩展。

支持数据库

此库应能在几乎所有使用基本SQL语法的数据库中正常工作。PDO支持的数据库和合适的驱动程序可在https://php.ac.cn/manual/en/pdo.drivers.php找到。

安装

composer require initorm/database

用法

QueryBuilder & DBAL 和 CRUD

require_once "vendor/autoload.php";
use \InitORM\Database\Facade\DB;

// Connection
DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
]);

创建

use \InitORM\Database\Facade\DB;
$data = [
    'title'     => 'Post Title',
    'content'   => 'Post Content',
];

$isInsert = DB::create('post', $data);

/**
* This executes the following query.
* 
* INSERT INTO post 
* (title, content) 
* VALUES 
* ("Post Title", "Post Content");
*/
if($isInsert){
    // Success
} else {
    foreach (DB::getErrors() as $errMsg) {
        echo $errMsg;
    }
}
批量创建
use \InitORM\Database\Facade\DB;

$data = [
    [
        'title'     => 'Post Title 1',
        'content'   => 'Post Content 1',
        'author'    => 5
    ],
    [
        'title'     => 'Post Title 2',
        'content'   => 'Post Content 2'
    ],
];

$isInsert = DB::createBatch('post', $data);

/**
* This executes the following query.
* 
* INSERT INTO post 
* (title, content, author) 
* VALUES 
* ("Post Title 1", "Post Content 1", 5),
* ("Post Title 2", "Post Content 2", NULL);
*/

if($isInsert){
    // Success
}

读取

use \InitORM\Database\Facade\DB;


/**
* This executes the following query.
* 
* SELECT user.name AS author_name, post.id, post.title 
* FROM post, user 
* WHERE user.id = post.author AND post.status = 1
* ORDER BY post ASC, post.created_at DESC
* LIMIT 20, 10
*/

$res = DB::select('user.name as author_name', 'post.id', 'post.title')
    ->from('post')
    ->selfJoin('user', 'user.id=post.author')
    ->where('post.status', 1)
    ->orderBy('post.id', 'ASC')
    ->orderBy('post.created_at', 'DESC')
    ->offset(20)->limit(10)
    ->read();
    
if($res->numRows() > 0){
    $results = $res->asAssoc()
                    ->rows();
    foreach ($results as $row) {
        echo $row['title'] . ' by ' . $row['author_name'] . '<br />';
    }
}

更新

use \InitORM\Database\Facade\DB;
$data = [
    'title'     => 'New Title',
    'content'   => 'New Content',
];

$isUpdate = DB::where('id', 13)
                ->update('post', $data);
    
/**
* This executes the following query.
* 
* UPDATE post 
* SET title = "New Title", content = "New Content"
* WHERE id = 13
*/
if ($isUpdate) {
    // Success
}
批量更新
use \InitORM\Database\Facade\DB;
$data = [
    [
        'id'        => 5,
        'title'     => 'New Title #5',
        'content'   => 'New Content #5',
    ],
    [
        'id'        => 10,
        'title'     => 'New Title #10',
    ]
];

$isUpdate = DB::where('status', '!=', 0)
                ->updateBatch('id', 'post', $data);
    
/**
* This executes the following query.
* 
* UPDATE post SET 
* 	title = CASE 
* 		WHEN id = 5 THEN 'New Title #5' 
* 		WHEN id = 10 THEN 'New Title #10' 
* 		ELSE title END, 
* 	content = CASE 
* 		WHEN id = 5 THEN 'New Content #5'
* 		ELSE content END 
* WHERE status != 0 AND id IN (5, 10)
*/
if ($isUpdate) {
    // Success
}

删除

use \InitORM\Database\Facade\DB;

$isDelete = DB::where('id', 13)
                ->delete('post');
    
/**
* This executes the following query.
* 
* DELETE FROM post WHERE id = 13
*/
if ($isUpdate) {
    // Success
}

原始(RAW)

use \InitORM\Database\Facade\DB;

$res = DB::query("SELECT id, title FROM post WHERE user_id = :id", [
    ':id'   => 5
]);

if ($res->numRows() > 0) {
    $result = $res->asObject()
                    ->row();
    
    echo $result->title;
}

RAW 构建器

use \InitORM\Database\Facade\DB;

$res = DB::select(DB::raw("CONCAT(name, ' ', surname) AS fullname"))
        ->where(DB::raw("title = '' AND (status = 1 OR status = 0)"))
        ->limit(5)
        ->read('users');
        
/**
 * SELECT CONCAT(name, ' ', surname) AS fullname 
 * FROM users 
 * WHERE title = '' AND (status = 1 OR status = 0)
 * LIMIT 5
 */
$results = $res->asAssoc()
                ->rows();
foreach ($results as $row) {
    echo $row['fullname'];
}

使用不同的连接

此库的开发思想是您将使用单个数据库和连接,但我知道在某些项目中您会使用多个连接和数据库。

如果您想使用不同的非全局连接,请使用 connect() 方法。

use \InitORM\Database\Facade\DB;

DB::connect([
    'dsn'       => 'mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
]);

开发工具

以下是我提到的您在开发和开发后可以使用的一些开发者工具。

日志记录器

use \InitORM\Database\Facade\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'log'       => __DIR__ '/logs/db.log', // string, callable or object
]);

如果您将文件路径定义为字符串,则尝试使用 file_put_contents() 将内容写入其中。

注意:您可以在文件名中定义如 {year}{month}{day} 这样的变量。

  • 您还可以使用 critical 方法定义一个对象。数据库库将日志消息作为参数传递给此方法。或者将其定义为可调用的数组以使用对象中的任何方法。
use \InitORM\Database\Facade\DB;

class Logger {
    
    public function critical(string $msg)
    {
        $path = __DIR__ . '/log.log';
        file_put_contents($path, $msg, FILE_APPEND);
    }

}

$logger = new Logger();

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'log'       => $logger, // or [$logger, 'critical']
]);
  • 同样,也可以在可调用的方法中定义它。
use \InitORM\Database\Facade\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'log'       => function (string $msg) {
        $path = __DIR__ . '/log.log';
        file_put_contents($path, $msg, FILE_APPEND);
    },
]);

调试模式

调试模式用于在错误消息中包含执行的SQL语句。它只应在开发环境中激活

use \InitORM\Database\Facade\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'debug'     => true, // boolean
]);

分析模式

分析模式是v3及以上版本中可用的一种开发者工具。这是一个允许您查看执行查询及其执行时间的功能。

use InitPHP\Database\Facade\DB;

DB::enableQueryLog();

DB::table('users')->where('name', 'John')->read();

var_dump(DB::getQueryLogs());

/**
 * The output of the above example looks like this;
 * [
 *      [
 *          'query' => 'SELECT * FROM users WHERE name = :name',
 *          'time'  => '0.00064',
 *          'args'  => [
 *              ':name'     => 'John',
 *          ]
 *      ]
 * ]
 * 
 */

获取帮助

如果您有任何问题、担忧、错误报告等,请在本存储库的问题跟踪器中提交问题。

参与其中

本项目所有贡献均将在MIT许可证下发布。通过提交拉取请求或提交错误、问题或功能请求,您同意遵守此版权利益放弃声明。

有两种主要的方式可以帮助

  • 使用问题跟踪器,和
  • 更改代码库。

使用问题跟踪器

使用问题跟踪器提出功能请求、报告错误和提问。这也是与项目开发人员以及对此解决方案感兴趣的其他人建立联系的好方法。

使用问题跟踪器寻找贡献方式。找到一个错误或功能,在问题中说明您将承担这项工作,然后遵循下面更改代码库的指南。

更改代码库

一般来说,您应该对这个仓库进行分支,在自己的分支中进行更改,然后提交拉取请求。所有新的代码都应该有与之相关的单元测试,以验证实现的功能和缺陷的存在或不存在。此外,代码应遵循项目规定的任何样式和架构指南。如果没有这样的指南,则模仿现有代码库中的样式和模式。

致谢

许可证

版权所有 © 2023 MIT 许可证