php-patterns/activerecord

php-activerecord 是一个基于 ActiveRecord 模式的开源 ORM 库。

2.0.2 2023-11-29 22:33 UTC

README

CI codecov Latest Stable Version

logo_large

我们鼓励提交拉取请求,并将及时、全面地处理问题。

http://php-activerecord.github.io/activerecord/

安装

通过 composer

composer require php-patterns/activerecord

简介

ActiveRecord 的简要概述

Active record 是一种访问数据库数据的方法。数据库表或视图被封装成类,因此对象实例与表中的一行相关联。创建对象后,在保存时会在表中添加新行。任何加载的对象都从数据库获取其信息;当对象更新时,表中的对应行也会更新。包装类为表或视图中的每一列实现了访问器方法或属性。

更多详细信息请见此处

此实现受 Ruby on Rails 的 ActiveRecord 的启发,因此大量借鉴了其设计。我们试图保持其约定,但由于便利或必要性而有所偏离。当然,对于熟悉 Rails 的用户来说,有一些差异将是显而易见的。

最低要求

支持的数据库

  • MySQL
  • PostgreSQL
  • SQLite

功能

  • 回调
  • 模型缓存
  • 数据库适配器插件
  • 查找方法,静态和动态
  • 关系
  • 序列化(json/xml)
  • 事务
  • 验证
  • 写入方法
  • 其他选项,例如:别名/受保护/可访问属性

安装

设置非常简单直接。基本上只有两个配置点你需要关注

  1. 配置数据库连接。
  2. 设置用于您的环境的数据库连接。

示例

$cfg = ActiveRecord\Config::instance();
$cfg->set_connections([
    'development' => 'mysql://username:password@localhost/development_database_name',
    'test' => 'mysql://username:password@localhost/test_database_name',
    'production' => 'mysql://username:password@localhost/production_database_name'
]);
$cfg->set_default_connection('development'); // Set to 'development', 'test', or 'production'. 'development' is default

一旦配置了这些设置,你就完成了。ActiveRecord 会为你处理剩下的工作。它不需要你将表模式映射到 yaml/xml 文件中。它会查询数据库以获取这些信息,并将其缓存起来,这样就不会对单个模式进行多次数据库调用。

基本 CRUD

检索

这些是您从数据库中查找和检索记录的基本方法。有关更多详细信息,请参阅 查找器 部分。

$post = Post::find(1);
echo $post->title; # 'My first blog post!!'
echo $post->author_id; # 5

# also the same since it is the first record in the db
$post = Post::first();

# finding using dynamic finders
$post = Post::find_by_name('The Decider');
$post = Post::find_by_name_and_id('The Bridge Builder',100);
$post = Post::find_by_name_or_id('The Bridge Builder',100);

# finding using a conditions array
$posts = Post::find('all', ['conditions' => ['name=? or id > ?','The Bridge Builder',100]]);

创建

在这里,我们通过实例化一个新对象并调用 save() 方法来创建一个新的帖子。

$post = new Post();
$post->title = 'My first blog post!!';
$post->author_id = 5;
$post->save();
# INSERT INTO `posts` (title,author_id) VALUES('My first blog post!!', 5)

更新

要更新,您首先需要找到一条记录,然后更改其属性之一。它保留一个包含“脏”属性(已被修改)的数组,因此我们的 sql 将仅更新已修改的字段。

$post = Post::find(1);
echo $post->title; # 'My first blog post!!'
$post->title = 'Some real title';
$post->save();
# UPDATE `posts` SET title='Some real title' WHERE id=1

$post->title = 'New real title';
$post->author_id = 1;
$post->save();
# UPDATE `posts` SET title='New real title', author_id=1 WHERE id=1

删除

删除记录不会 销毁 对象。这意味着它将调用 sql 删除数据库中的记录,但如果你需要,你仍然可以使用该对象。

$post = Post::find(1);
$post->delete();
# DELETE FROM `posts` WHERE id=1
echo $post->title; # 'New real title'

贡献

有关如何为 PHP ActiveRecord 做出贡献的信息,请参阅 CONTRIBUTING.md