flightphp/active-record

PHP 微型Active Record库,支持链式调用、事件和关系。

v0.4.9 2024-07-30 01:27 UTC

README

Latest Stable Version License PHP Version Require Dependencies

Active Record 将数据库实体映射到PHP对象。简单来说,如果你的数据库中有users表,你可以将表中的某一行“翻译”为你的代码库中的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