voku/simple-active-record
Composer 安装命令:
composer require voku/simple-active-record
包简介
Simple Active Record
关键字:
README 文档
README
💍 Simple Active Record
This is a simple Active Record Pattern compatible with PHP 7+ that provides a simple and secure interaction with your database using 💎 "Simple MySQLi" at its core. This is perfect for small scale applications such as cron jobs, facebook canvas campaigns or micro frameworks or sites.
Get "Simple Active Record"
You can download it from here, or require it using composer.
{
"require": {
"voku/simple-active-record": "1.*"
}
}
Install via "composer require"
composer require voku/simple-active-record
- Starting the driver
- Multiton && Singleton
- Doctrine/DBAL as parent driver
- Using the "ActiveRecord"-Class (OOP database-access)
- Logging and Errors
- Changelog
Starting the driver
use voku\db\DB; require_once 'composer/autoload.php'; $db = DB::getInstance('yourDbHost', 'yourDbUser', 'yourDbPassword', 'yourDbName'); // example // $db = DB::getInstance('localhost', 'root', '', 'test');
Multiton && Singleton
You can use DB::getInstance() without any parameters and you will get your (as "singleton") first initialized connection. Or you can change the parameter and you will create an new "multiton"-instance which works like an singleton, but you need to use the same parameters again, otherwise (without the same parameter) you will get an new instance.
Doctrine/DBAL as parent driver
use voku\db\DB; require_once 'composer/autoload.php'; $connectionParams = [ 'dbname' => 'yourDbName', 'user' => 'yourDbUser', 'password' => 'yourDbPassword', 'host' => 'yourDbHost', 'driver' => 'mysqli', // 'pdo_mysql' || 'mysqli' 'charset' => 'utf8mb4', ]; $config = new \Doctrine\DBAL\Configuration(); $doctrineConnection = \Doctrine\DBAL\DriverManager::getConnection( $connectionParams, $config ); $doctrineConnection->connect(); $db = DB::getInstanceDoctrineHelper($doctrineConnection);
Using the "ActiveRecord"-Class (OOP database-access)
A simple implement of active record pattern via Arrayy.
setDb(DB $db)
set the DB connection.
$db = DB::getInstance('YOUR_MYSQL_SERVER', 'YOUR_MYSQL_USER', 'YOUR_MYSQL_PW', 'YOUR_DATABASE'); ActiveRecord::setDb($db);
insert() : bool|int
This function can build insert SQL queries and can insert the current record into database. If insert was successful, it will return the new id, otherwise it will return false or true (if there are no dirty data).
$user = new User(); $user->name = 'demo'; $user->password = password_hash('demo', PASSWORD_BCRYPT, ["cost" => 15]); $user_id = $user->insert(); var_dump($user_id); // the new id var_dump($user->id); // also the new id var_dump($user->getPrimaryKey()); // also the new id
fetch(integer $id = null) : bool|\ActiveRecord
This function can fetch one record and assign in to current object. If you call this function with the $id parameter, it will fetch records by using the current primary-key-name.
$user = new User(); $user->notnull('id')->orderBy('id desc')->fetch(); // OR // $user->fetch(1); // OR // $user->fetchById(1); // thows "FetchingException" if the ID did not exists // OR // $user->fetchByIdIfExists(1); // return NULL if the ID did not exists // OR // $user->fetchByHashId('fsfsdwldasdar'); // thows "FetchingException" if the ID did not exists // OR // $user->fetchByHashIdIfExists('fsfsdwldasdar'); // return NULL if the ID did not exists var_dump($user->id); // (int) 1 var_dump($user->getPrimaryKey()); // (int) 1
fetchAll() : $this[]
This function can fetch all records in the database and will return an array of ActiveRecord objects.
$user = new User(); $users = $user->fetchAll(); // OR // $users = $user->fetchByIds([1]); // OR // $users = $user->fetchByIdsPrimaryKeyAsArrayIndex([1]); var_dump($users[0]->id) // (int) 1 var_dump($users[0]->getPrimaryKey()); // (int) 1
update() : bool|int
This function can build update SQL queries and can update the current record in database, just write the dirty data into database. If update was successful, it will return the affected rows as int, otherwise it will return false or true (if there are no dirty data).
$user = new User(); $user->notnull('id')->orderBy('id desc')->fetch(); $user->email = 'test@example.com'; $user->update();
delete() : bool
This function can delete the current record in the database.
Active Record | SQL part functions
select()
This function can set the select columns.
$user = new User(); $user->select('id', 'name')->fetch();
from()
This function can set the table to fetch record from.
$user = new User(); $user->select('id', 'name')->from('user')->fetch();
join()
This function can set the table to fetch record from.
$user = new User(); $user->join('contact', 'contact.user_id = user.id')->fetch();
where()
This function can set where conditions.
$user = new User(); $user->where('id=1 AND name="demo"')->fetch();
groupBy()
This function can set the "group by" conditions.
$user = new User(); $user->select('count(1) as count')->groupBy('name')->fetchAll();
orderBy()
This function can set the "order by" conditions.
$user = new User(); $user->orderBy('name DESC')->fetch();
limit()
This function can set the "limit" conditions.
$user = new User(); $user->orderBy('name DESC')->limit(0, 1)->fetch();
Active Record | WHERE conditions
equal()/eq()
$user = new User(); $user->eq('id', 1)->fetch();
notEqual()/ne()
$user = new User(); $user->ne('id', 1)->fetch();
greaterThan()/gt()
$user = new User(); $user->gt('id', 1)->fetch();
lessThan()/lt()
$user = new User(); $user->lt('id', 1)->fetch();
greaterThanOrEqual()/ge()/gte()
$user = new User(); $user->ge('id', 1)->fetch();
lessThanOrEqual()/le()/lte()
$user = new User(); $user->le('id', 1)->fetch();
like()
$user = new User(); $user->like('name', 'de')->fetch();
in()
$user = new User(); $user->in('id', [1, 2])->fetch();
notIn()
$user = new User(); $user->notin('id', [1, 3])->fetch();
isNull()
$user = new User(); $user->isnull('id')->fetch();
isNotNull()/notNull()
$user = new User(); $user->isNotNull('id')->fetch();
Active Record | Demo
Include && Init
use voku\db\DB; use voku\db\ActiveRecord; require_once 'composer/autoload.php'; $db = DB::getInstance('YOUR_MYSQL_SERVER', 'YOUR_MYSQL_USER', 'YOUR_MYSQL_PW', 'YOUR_DATABASE'); ActiveRecord::setDb($db);
Define Class
namespace demo; use voku\db\ActiveRecord; /** * @property int $id * @property string $name * @property string $password * @property Contact[] $contacts * @property Contact $contacts_with_backref * @property Contact $contact */ class User extends ActiveRecord { public $table = 'user'; public $primaryKey = 'id'; protected function init() { $this->addRelation( 'contacts', self::HAS_MANY, FoobarContact::class, 'user_id' ); $this->addRelation( 'contacts_with_backref', self::HAS_MANY, FoobarContact::class, 'user_id', null, 'user' ); $this->addRelation( 'contact', self::HAS_ONE, FoobarContact::class, 'user_id', [ self::SQL_WHERE => '1 = 1', self::SQL_ORDER => 'id desc', ] ); } } /** * @property int $id * @property int $user_id * @property string $email * @property string $address * @property User $user_with_backref * @property User $user */ class Contact extends ActiveRecord { public $table = 'contact'; public $primaryKey = 'id'; protected function init() { $this->addRelation( 'user_with_backref', self::BELONGS_TO, FoobarUser::class, 'user_id', null, 'contact' ); $this->addRelation( 'user', self::BELONGS_TO, FoobarUser::class, 'user_id' ); } }
Init data (for testing - use migrations for this step, please)
CREATE TABLE IF NOT EXISTS user ( id INTEGER PRIMARY KEY, name TEXT, password TEXT ); CREATE TABLE IF NOT EXISTS contact ( id INTEGER PRIMARY KEY, user_id INTEGER, email TEXT, address TEXT );
Insert one User into database.
use demo\User; $user = new User(); $user->name = 'demo'; $user->password = password_hash('demo', PASSWORD_BCRYPT, ["cost" => 15]); $user_id = $user->insert(); var_dump($user_id); // the new id var_dump($user->id); // also the new id var_dump($user->getPrimaryKey()); // also the new id
Insert one Contact belongs the current user.
use demo\Contact; $contact = new Contact(); $contact->address = 'test'; $contact->email = 'test1234456@domain.com'; $contact->user_id = $user->id; var_dump($contact->insert()); // the new id var_dump($contact->id); // also the new id var_dump($contact->getPrimaryKey()); // also the new id
Example to using relations
use demo\User; use demo\Contact; $user = new User(); // fetch one user var_dump($user->notnull('id')->orderBy('id desc')->fetch()); echo "\nContact of User # {$user->id}\n"; // get contacts by using relation: // 'contacts' => [self::HAS_MANY, 'demo\Contact', 'user_id'], var_dump($user->contacts); $contact = new Contact(); // fetch one contact var_dump($contact->fetch()); // get user by using relation: // 'user' => [self::BELONGS_TO, 'demo\User', 'user_id'], var_dump($contact->user);
Changelog
See CHANGELOG.md.
Support
For support and donations please visit Github | Issues | PayPal | Patreon.
For status updates and release announcements please visit Releases | Twitter | Patreon.
For professional support please contact me.
Thanks
- Thanks to GitHub (Microsoft) for hosting the code and a good infrastructure including Issues-Managment, etc.
- Thanks to IntelliJ as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
- Thanks to Travis CI for being the most awesome, easiest continous integration tool out there!
- Thanks to StyleCI for the simple but powerfull code style check.
- Thanks to PHPStan && Psalm for relly great Static analysis tools and for discover bugs in the code!
voku/simple-active-record 适用场景与选型建议
voku/simple-active-record 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 561 次下载、GitHub Stars 达 5, 最近一次更新时间为 2018 年 12 月 21 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「db」 「Active Record」 「simple db」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 voku/simple-active-record 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 voku/simple-active-record 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 voku/simple-active-record 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Propel2 is an open-source Object-Relational Mapping (ORM) for PHP 5.5 and up.
PHP Interface for Babel Street Text Analytics
A Symfony extension to get active class base on current bundle/controller/action
LDAP user provider bundle for Symfony 6.4
The helper class for Laravel applications to get active class base on current route for Laravel 11
Anax Database Active Record module for model classes.
统计信息
- 总下载量: 561
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 5
- 点击次数: 3
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-12-21