irfantoor / database
Irfan's Database - 简单且基础的数据库访问
Requires
- php: >=7.3
Requires (Dev)
- irfantoor/test: ~0.8
README
轻松创建模型和/或访问您的数据库,最少开销和最简单的数据库访问。
安装
$ composer require irfantoor/database
创建数据库对象
方法: new Database(?array $connection = null)
参数:
- array $connection - 包含数据库引擎(如MySQL、SQLite等)所需参数的连接数组
返回: 数据库对象
示例:
<?php $db = new Database( [ 'type' => 'sqlite', 'file' => 'posts.sqlite' ] );
连接到数据库引擎
方法: connect(array $connection)
参数:
- array $connection
返回:
- true - 如果数据库引擎成功连接
- false - 如果无法连接到引擎
示例:
<?php # a database object is created, but it needs to be connected to a database # before querring $db = new Database(); # for sql $connection = [ 'type' => 'sqlite', 'file' => 'storage_path/users.sqlite', ]; # for mysql $connection = [ 'type' => 'mysql', 'host' => 'localhost', 'user' => 'root', 'password' => 'toor', 'db_name' => 'test', ]; $db->connect($connection); # Note: the definition of 'type' in connection is obligatory.
传递给数据库引擎的操作
执行原始SQL
方法: query(string $sql, array $data = [])
参数:
- string $sql,
- array $bind - 绑定关联数组到在准备SQL时绑定的数据
返回:
- true or false - 如果查询类型是UPDATE、INSERT和DELETE
- array - 返回SELECT查询的结果
示例:
<?php $result = $db->query('SECLECT count(*) from users where valid=true');
将记录插入到连接的数据库中
方法: insert(string $table, array $record, array $bind = [])
参数:
- string $table - 要查询的表
- array $record - 记录的关联数组
Values might contain variables of the form :id etc, which are filled using the prepare
mechanism, taking data from bind array e.g. ['id' => :id, 'name' => :name ]
注意:记录必须包含所有必需的字段
- array $bind - 关联数组,例如
['id' => $_GET['id'] ?? 1]
返回:
- true - 如果记录已插入
- false - 记录未插入
示例:
<?php $db->insert('users', ['name' => 'Fabien Potencier', 'email' => 'fabien@symfony.com']); # OR $user = [ 'name' => 'Irfan TOOR', 'email' => 'email@irfantoor.com', 'password' => 'its-a-test', ]; $db->insert('users', $user); # NOTE: the query will be prepared and values will be bound automatically
更新现有记录
方法: update(string $table, array $record, array $options = [])
参数:
- string $table
- array $record - 仅包含要更新的数据的关联数组
e.g $record = [
'id' => 1,
'user' => 'root',
'password' => 'toor',
'groups' => 'admin,user,backup',
'remote' => false,
];
- array $options 包含where、limit或bind等
e.g $options = [
'where' => 'id = :id', <------------+
'limit' => 1, |
'bind' => [ |
'id' => $_GET['root_id'] ?? 1, -+
]
];
如果没有提供选项,以下为默认值
- 'where' => '1 = 1',
- 'limit' => 1, // see DatabaseEngineInterface::get
- 'bind' => [],
返回:
- true - 如果成功
- false - 否则
示例:
<?php $db->update('users', [ 'password' => $new_password, ], [ 'where' => 'email = :email', 'bind' => [ 'email' => $email ] ] );
从数据库中删除记录
方法: remove(string $table, array $options)
参数:
- string $table
- array $options 包含where、limit或bind选项。如果没有提供选项,以下为默认值
[
'where' => '1 = 0', # forces that a where be provided
'limit' => 1, # see DatabaseEngineInterface::get
'bind' => [], # see DatabaseEngineInterface::update
]
返回:
- true - 如果成功删除
- false - 否则
示例:
<?php $db->remove( 'users', [ 'where' => 'email = :email', 'bind' => [ 'email' => $email ] ] );
检索记录列表
方法: get(string $table, array $options = [])
参数:
- string $table
- array $options - 包含where、order_by、limit和bind的关联数组
如果limit是一个整数,则从开始检索记录,如果它是一个数组,则解释为[int $from, int $count],$from指示要跳过的记录数,$count指示要检索的记录数。
e.g. $options = [
'limit' => 1 or 'limit' => [0, 10]
'order_by' => 'ASC id, DESC date',
'where' => 'date < :date', <---------------------------+
'bind' => ['date' => $_POST['date'] ?? date('d-m-Y')], +
# bind: see DatabaseEngineInterface::update
];
返回:
包含行数组的数组[row ...] 或如果没有找到则为null
示例:
<?php $list = $db->get('posts', [ 'where' => 'created_at like :date', 'order_by' => 'created_at DESC, id DESC', 'limit' => [0, 10], 'bind' => ['date' => '%' . $_GET['date'] . '%'] ]);
仅检索第一条记录
方法: getFirst(string $table, array $options = []);
参数:
- string $table - 表名,例如 $table = 'users';
- array $options 如DatabaseEngineInterface::get中所述
返回:
包含行键值对的数组 或如果没有找到则为null
示例:
<?php $last_post = $db->getFirst('posts', ['orderby' => 'date DESC']);
数据库模型
注意: 当前模型仅支持SQLite数据库
模型使用数据库和上述解释的调用。由于模型与表相关联,因此对模型的调用(数据库的)与数据库的调用相同,只是方法中的第一个参数table_name不存在。
创建模型
示例: Models\Users.php
<?php namespace Models\Users; use IrfanTOOR\Database\Model; class Users extends Model { function __construct($connection) { # schema needs to be defined $this->schema = [ 'id' => 'INTEGER PRIMARY KEY', 'name' => 'NOT NULL', 'email' => 'COLLATE NOCASE', 'password' => 'NOT NULL', 'token', 'validated' => 'BOOL DEFAULT false', 'created_on' => 'DATETIME DEFAULT CURRENT_TIMESTAMP', 'updated_on' => 'INTEGER' ]; # indices need to be defined $this->indices = [ ['index' => 'name'], ['unique' => 'email'], ]; # call the constructor with the $connection parent::__construct($connection); } }
模型构造函数
方法: $users = new Users(array $connection)
参数:
- array $connection - ['file' => $db_path . 'users.sqlite', 'table' => 'users']
返回:
Users模型对象
示例:
<?php use Model\Users; $connection = [ 'file' => $db_path . 'users.sqlite', 'table' => 'users' ]; # NOTE: If table name is not provided Model name e.g. 'Users' will be converted # to lowercase i.e. 'users' and will be used as table name. $users = new Users($connection);
检索数据库文件名
方法: getDatabaseFile()
参数: 无
返回:
string - 模型连接到的 sqlite 文件的路径名
示例:
<?php $file = $users->getDatabaseFile();
从模型定义准备数据库模式并返回它
方法: prepareSchema()
参数: 无
返回:
string - 原始 SQL 模式,由提供的模式定义和索引(参见:创建模型)准备而成,可以用来手动创建 sqlite 文件。
示例:
<?php $schema = $users->prepareSchema(); echo $schema;
部署模式
方法: deploySchema(string $schema)
参数:
- string $schema - 要部署到连接文件中的模式
抛出: Exception - 出现错误时
返回: 无
示例:
<?php $file = $sb_path . 'users.sqlite'; # create a file and deploy the schema if it does not exist if (!file_exists($file)) { file_put_contents($file, ''); $users = new Users(['file' => $file]); $schema = $users->prepareSchema(); $users->deploySchema($schema); }
插入记录
方法: insert(array $record, array $bind = [])
参数:
- array $record - 记录的关联数组
值可能包含形式为 :id 等的变量,这些变量将通过准备机制填充,从绑定数组中获取数据,例如 ['id' => :id, 'name' => :name] 注意:record 必须包含所有必需的字段
- array $bind - 我们需要绑定到 $record 中 :占位符的数据
返回:
- true - 如果成功插入记录
- false - 否则
示例:
<?php $user = [ 'name' => 'Irfan TOOR', 'email' => 'email@irfantoor.com', 'password' => 'some-password', ]; $users->insert($user);
插入或更新记录
此方法在记录不存在时插入记录,或在存在时更新现有记录。
方法: insertOrUpdate(array $record, array $bind = [])
参数:
- array $record - 代表一个记录的关联数组
- array $bind - 我们需要绑定到 $record 中 :占位符的数据
返回:
- true - 如果成功插入或更新记录
- false - 否则
示例:
<?php $user['password'] = 'password-to-be-updated'; $users->insertOrUpdate($user); # updates the record of previous example $user = [ 'name' => 'Some User', 'email' => 'email@example.com', 'password' => 'some-password', ]; $users->insertOrUpdate($user); # inserts the record now
更新现有记录
方法: update(array $record, array $options = [])
参数:
- array $record - 代表一个记录的关联数组
- array $options - where 子句或绑定数据等。
返回:
- true - 如果成功更新记录
- false - 否则
示例:
<?php $email = 'email@example.com'; $users->update( # only the record data which we need to modify [ 'password' => 'password', ], # options [ 'where' => 'email = :email', 'bind' => [ 'email' => $email ] ] );
删除现有记录
方法: remove(array $options)
参数:
- array $options - where 子句或绑定数据等。
返回:
- true - 如果成功删除记录
- false - 否则
示例:
<?php $users->remove([ 'where' => 'email = :email', 'bind' => [ 'email' => $email ] ]);
检索记录列表
方法: get(array $options = [])
参数:
- array $options - where 子句或绑定数据等。
返回: array 或 records 或 null
示例:
<?php $list = $users->get(); $list = $users->get(['where' => 'validated = true']); $list = $posts->get( [ 'where' => 'created_at like :date', 'order_by' => 'created_at DESC, id DESC', 'limit' => [0, 10], 'bind' => ['date' => '%' . $_GET['date'] . '%'] ] );
检索第一条记录
方法: getFirst(array $options = [])
参数:
- array $options - where 子句或绑定数据等,可能包括 order_by 和 limit 参数
返回:
- array - 包含记录的关联数组
- null - 如果找不到
示例:
<?php $user = $users->getFirst(); $last_post = $posts->getFirst(['orderby' => 'date DESC']);
验证记录是否存在
方法: has($options = [])
参数:
- array $options - where 子句或绑定数据等。
返回:
- true - 如果记录存在
- false - 否则
示例:
<?php $users->has( [ 'where' => 'email = :email', 'bind' => [ 'email' =>$email, ] ] );