syan / active-record
PHP的微Active Record库,支持链式调用、事件和关系。
v0.4.6
2024-03-31 12:16 UTC
Requires
- php: >=7.4
Requires (Dev)
- ext-pdo_sqlite: *
- phpunit/phpunit: ^9.0
- rregeer/phpunit-coverage-check: ^0.3.1
- squizlabs/php_codesniffer: ^3.8
This package is not auto-updated.
Last update: 2024-09-30 09:38:49 UTC
README
Active Record将数据库实体映射到PHP对象。简单来说,如果你在数据库中有用户表,你可以将表中的一行“翻译”为代码库中的User
类和$user
对象。参见基本示例。
基本示例
假设你有一个以下表格
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
password TEXT
);
现在你可以设置一个新的类来表示这个表
/**
* An ActiveRecord class is usually singular
*
* It's highly recommended to add the properties of the table as comments here
*
* @property int $id
* @property string $name
* @property string $password
*/
class User extends flight\ActiveRecord {
public function __construct($databaseConnection)
{
parent::__construct($databaseConnection, 'users', [ /* custom values */ ]);
}
}
现在看看魔法发生了!
// for sqlite
$database_connection = new PDO('sqlite:test.db'); // this is just for example, you'd probably use a real database connection
// for mysql
$database_connection = new PDO('mysql:host=localhost;dbname=test_db&charset=utf8bm4', 'username', 'password');
// or mysqli
$database_connection = new mysqli('localhost', 'username', 'password', 'test_db');
// or mysqli with non-object based creation
$database_connection = mysqli_connect('localhost', 'username', 'password', 'test_db');
$user = new User($database_connection);
$user->name = 'Bobby Tables';
$user->password = password_hash('some cool password');
$user->insert();
// or $user->save();
echo $user->id; // 1
$user->name = 'Joseph Mamma';
$user->password = password_hash('some cool password again!!!');
$user->insert();
echo $user->id; // 2
添加新用户竟然这么简单!现在数据库中已经有一个用户行,你该如何检索它呢?
$user->find(1); // find id = 1 in the database and return it.
echo $user->name; // 'Bobby Tables'
如果你想找到所有用户呢?
$users = $user->findAll();
如果有一个特定的条件呢?
$users = $user->like('name', '%mamma%')->findAll();
看看这有多有趣?让我们安装它并开始吧!
安装
只需使用Composer安装
composer require flightphp/active-record
文档
前往文档页面了解用法和这个功能有多酷! :)
许可证
MIT