erusev/base

简单的数据库接口

0.2.0 2015-04-29 21:07 UTC

This package is auto-updated.

Last update: 2024-09-05 16:23:52 UTC


README

Base是一个简单的库,使PHP中与数据库工作更加容易。

我从2012年开始使用它,觉得现在是时候分享它了。

特性

  • 简单
  • 直观
  • 独立
  • 安全
  • 在5.3、5.4、5.5、5.6、7和HHVM上进行了测试

安装

包括Base.phpCollection.php,或者安装composer包

示例

连接到数据库

# the constructor takes the same parameters as the PDO constructor
$Base = new \Base\Base('mysql:host=localhost;dbname=example', 'username', 'password');

处理记录

# read user 1
$Base->readItem('user', 1);
# update the username of user 1
$Base->updateItem('user', 1, ['username' => 'john.doe']);
# create a user
$Base->createItem('user', ['username' => 'jane.doe', 'email' => 'jane@example.com']);
# delete user 1
$Base->deleteItem('user', 1);

处理集合

# read all users
$Base->find('user')->read();
# read the users that are marked as verified in a desc order
$Base->find('user')->whereEqual('is_verified', 1)->orderDesc('id')->read();
# read the user with the most reputation
$Base->find('user')->limit(1)->orderDesc('reputation')->readRecord();
# mark users 1 and 3 as verified
$Base->find('user')->whereIn('id', [1, 3])->update(['is_verified' => 1]);
# count the users that don't have a location
$Base->find('user')->whereNull('location')->count();
# plain sql conditions are also supported
$Base->find('user')->where('is_verified = ?', [1])->read();

处理关系

# read the users that have a featured post
$Base->find('user')->has('post')->whereEqual('post.is_featured', 1)->read();
# read the posts of user 1
$Base->find('post')->belongsTo('user')->whereEqual('user.id', 1)->read();
# read the posts that are tagged "php"
$Base->find('post')->hasAndBelongsTo('tag')->whereEqual('tag.name', 'php')->read();
# unconventional FK names are also supported
$Base->find('user')->has('post', 'author_id')->whereEqual('user.id', 1)->read();

执行查询

# read all users
$Base->read('SELECT * FROM user');
# read user 1
$Base->readRecord('SELECT * FROM user WHERE id = ?', [1]);
# read the username of user 1
$Base->readField('SELECT username FROM user WHERE id = ?', [1]);
# read all usernames
$Base->readFields('SELECT username FROM user');
# update all users
$Base->update('UPDATE user SET is_verified = ?', [1]);

注意

  • 未在其他RDBMS(如MySQL)上进行测试
  • 关系方法假设表名是单数形式 - 例如:使用user而不是users
  • 关系方法假设外键名以_id结尾 - 使用$fkEnding进行自定义