jamend/selective-orm

Selective 对象关系映射器

dev-master 2014-12-03 02:55 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:15:22 UTC


README

Selective ORM 是一个数据库抽象层,简化了与数据库的交互。它是完全面向对象的,并自动推断数据库模式(表/列/关系),因此您不需要在代码中重复。

  • 构建状态: 构建状态
  • 覆盖率状态: 覆盖率状态

安装

如果您想尝试 Selective 但尚未发布稳定版本,您可以将以下内容添加到您的 composer.json 中

{
    "require": {
        "jamend/selective-orm": "dev-master"
    }
}

用法

连接到数据库

// first argument is the database name
// second argument is the driver implementation class name
// third argument is the parameter array for the driver
$db = new \selective\ORM\Database(
	'sample',
	'MySQL', // driver class
	['host' => 'localhost', 'username' => '...', 'password' => '...'] // MySQL driver parameters
);

从数据库获取记录

$books = $db->Books; // get a Table instance for the Books table in the database

$book = $books->{12}; // get a Record instance for the book with ID 12

echo $book->title; // columns map directly to properties of the record

带有 where 和 order by 子句的记录循环

$someBooks = $db->Books
	->where('tite LIKE ?', 'The%')
	->orderBy('datePublished', 'DESC')
; // fluent interface

// $books will lazy-load the records once you start iterating through them
foreach ($someBooks as $id => $book) {
	echo "#{$id} => {$book->title} <br />";
}

无缓冲记录集

默认情况下,在开始迭代时将获取与查询匹配的所有行。当处理大量记录时,这可能导致性能问题,因为这些记录都保存在内存中,PHP 无法垃圾回收它们。作为替代方案,可以使用无缓冲记录集,这允许您像流式记录一样迭代结果

$bookStream = $books->
    ->orderBy('datePublished', 'DESC')
    ->unbuffered() // switch to unbuffered
;

foreach ($bookStream as $book) {
    // ...
}

持久化更改

创建书籍

$newBook = $books->create();
$newBook->title = 'A New Book';
$newBook->datePublished = time();
$newBook->save();

// $newBook's id is automatically set to the auto-increment ID
echo "New book created with ID {$newBook->getID()}";

更新书籍

$book = $books->{13};
$book->title = 'A Better Title';
$book->save();

删除书籍

$books->{14}->delete();

关系

Selective 还可以简化在模式中定义的关系(外键约束)的使用。

每个关系都将通过列名映射到表的列。如果列具有关系,则生成的记录属性将代表关系另一端的记录。

以下是一些示例

获取一本书的作者

$book = $books->{15};
$author = $book->idAuthor; // $author will be a Record for the author matching the book's idAuthor
echo $author->name;

获取一个作者的所有书籍

$authors = $db->Authors;

$author = $authors->{1};
$books = $author->Books; // $books will be the Books table filtered by the author

设置一本书的作者

$author = $authors->{2}
$book = $books->{16};

$book->idAuthor = $author; // '2' would also work
$book->save();

关系优化

默认情况下,相关记录是延迟加载的,这意味着 $book->idAuthor 或 $author->Books 的作者记录集不会在请求之前加载。当批量处理记录集及其相关记录时,这可能会引起不希望的情况,因为它会导致在循环中调用许多数据库查询。为了演示

foreach ($db->Books as $book) {
	// to get every book's author's name, a query must be sent to the database to fetch the book's author
	echo $book->idAuthor->name;
}

为了避免这种情况,可以使用 RecordSet::with($tableName) 方法来告诉 Selective 预先加载 RecordSet 的相关记录

foreach ($db->Books->with('Authors') as $book) {
	// the author for each book will already be pre-loaded using the same query that fetched the books
	echo $book->idAuthor->name;
}