musicman3/cruder

基于PDO的CRUD查询构建器

v1.0.8 2023-05-09 00:21 UTC

README

项目安装: composer require musicman3/cruder

Cruder项目是一个基于查询构建器原则和PDO操作数据库的CRUD系统。此项目主要用于eMarket项目:[https://github.com/musicman3/eMarket](https://github.com/musicman3/eMarket)

同时,该库被提取为独立项目,以便任何喜欢Cruder的人都可以将其用于自己的项目。

此项目的主要优点是库体积小、性能良好。此外,Cruder最初会检查所有输出数据以防止XSS注入。由于我们使用PDO,这使我们能够通过内置方法消除SQL注入。

要开始使用Cruder,您需要初始化数据库设置。初始化后,您可以执行CRUD操作。工作完成后,您需要关闭数据库连接。以下是一个示例:

use \Cruder\Db;

// DB settings
Db::set([
        'db_type' => 'mysql',
        'db_server' => 'localhost',
        'db_name' => 'my_base',
        'db_username' => 'root',
        'db_password' => 'my_password',
        'db_prefix' => 'emkt_',
        'db_port' => '3306',
        'db_family' => 'innodb',
        'db_charset' => 'utf8mb4',
        'db_collate' => 'utf8mb4_unicode_ci',
        'db_error_url' => '/my_error_page/?error_message=' // optional
    ]);

// Here we perform various actions that you will need for your project.
Db::connect()->read('my_table')
                ->selectAssoc('id')
                ->where('order >=', 5)
                ->orderByDesc('id')
                ->save();

// Close DB connect
Db::close();

有各种与数据库交互的方法。所有这些方法都使用PHPDoc和PHPDoc标签根据PSR-5和PSR-19标准进行了文档说明。在构建查询时使用调用链。以下是一个示例:

// Read (SELECT)
$id = Db::connect()
                ->read('my_table')
                ->selectAssoc('id')
                ->where('order >=', 5)
                ->orderByDesc('id')
                ->save();

// Create (INSERT INTO)
Db::connect()
         ->create('my_table')
         ->set('id', 10)
         ->set('order', 5)
         ->set('text', 'This is my text')
         ->save();

// Update
Db::connect()
         ->update('my_table')
         ->set('text', 'This is my new text')
         ->where('id =', 10)
         ->or('order >=' 5)
         ->save();

// Delete
Db::connect()
         ->delete('my_table')
         ->where('id =', 10)
         ->save();

// use DB-functions -> for example YEAR(date_created)
$data = Db::connect()
                ->read('my_table')
                ->selectAssoc('id, name, {{YEAR->date_created}}')
                ->where('{{YEAR->date_created}} =', '2021-04-21 20:38:40')
                ->orderByDesc('id')
                ->save();

// DB Install
Db::connect()->dbInstall('/full_path_to_db_file/db.sql', 'db_prefix');

// DROP TABLE
Db::connect()->drop('my_table')->save();

使用自己的语法与数据库函数交互,允许您同时使用多种类型的数据库。例如,您可以使用MySQL或Postgres。可以通过数据库适配器部分找到的模式添加新函数。对于MySQL,该模式位于Mysql/DbFunctions->pattern()

所有可用方法均可在CrudInterface.php文件中查看,或者通过在IDE中查看这些方法的描述和使用工具提示来查看。

使用的PHP标准建议

  • PSR-1 (基本编码标准)
  • PSR-4 (自动加载标准)
  • PSR-5 (PHPDoc标准)
  • PSR-12 (扩展编码风格指南)
  • PSR-19 (PHPDoc标签)