fforattini / simpleorm
SimpleORM
Requires
- doctrine/dbal: ^2.5
- icanboogie/inflector: ^1.4
- ramsey/uuid: ^3.5
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-28 20:25:19 UTC
README
SimpleORM 是一个用于处理 Entity 和 Repository 抽象的直观包。
此包使用 Doctrine\DBAL 包进行开发,以确保开发的质量和多功能性。
开始使用
安装
使用 Composer 安装
composer require "fforattini/simpleorm"
阅读单元测试文件,以便更快地理解包
如何使用
SimpleORM 有两个抽象 Entity 和 Repository。
Entity
Entity 应该代表数据库中的一个表。
use SimpleORM\Entity; class Book extends Entity { }
自定义属性
大多数 Entity 属性都是由 SimpleORM 定义的,但当然您可以定义自己的值
protected static $_table将使用包icanboogie/inflector定义为类名的复数形式;
示例
use SimpleORM\Entity; class Book extends Entity { public static $_table = 'my_books_table'; }
属性
Entity 类扩展了 ArrayObject!因此,您有各种方式可以处理您的属性
$book = new Book(); $book->id = '02adee84-a128-4e51-8170-4155ea222fae'; $book->name = 'My book'; // OR $book = new Book([ 'id' => '02adee84-a128-4e51-8170-4155ea222fae', 'name' => 'My book', ]);
在这里通过文档了解 ArrayObject 的更多信息。
模拟数据
只需定义一个使用 fzaninotto/faker 的元素工厂(更多关于这个 信息请见文档)
use Faker\Generator; use Ramsey\Uuid\Uuid; use SimpleORM\Entity; class Book extends Entity { public static function defineFactory(Generator $faker) { return [ 'id' => Uuid::uuid4(), 'name' => $faker->sentence(5, true), ]; } }
然后您可以简单调用
$book = Book::factory();
或者,您可以直接传递一个 callable 参数,您将接收到一个 Generator 实例
use Ramsey\Uuid\Uuid; $book = Book::factory(function($faker){ return [ 'id' => Uuid::uuid4(), 'name' => $faker->sentence(5, true), ]; });
创建表
您可以通过函数 Entity::defineTable(Table $table) 使用 Doctrine\DBAL\Schema\Table 实例来定义您的表
use SimpleORM\Entity; use SimpleORM\TableCreator; use Doctrine\DBAL\Schema\Table; class Book extends Entity implements TableCreator { public static function defineTable(Table $table) { $table->addColumn('id', 'string', [ 'length' => 36, 'unique' => true, ]); $table->addColumn('name', 'string'); $table->addUniqueIndex(["id"]); $table->setPrimaryKey(['id']); return $table; } }
您需要使用 Doctrine\DBAL\DriverManager 获取 Connection(更多关于这个 信息请见文档)并创建您的表
$schema = DriverManager::getConnection([ 'driver' => 'pdo_sqlite', 'path' => 'database.sqlite', ])->getSchemaManager();
然后您可以使用您创建的连接使用以下方法创建您的表
$schema->createTable(Book::getTable());
或者,您可以直接传递一个 callable 参数,您将接收到一个 Generator 实例
use SimpleORM\Entity; $schema->createTable(Entity::getTable(function($table){ $table->addColumn('id', 'string', [ 'length' => 36, 'unique' => true, ]); $table->addColumn('name', 'string'); $table->addUniqueIndex(["id"]); $table->setPrimaryKey(['id']); return $table; }));
Repository
Repository 应该处理一组 Entity 对象,并实现 SplDoublyLinkedList(您可以在这里了解更多 信息)。
在这里,所有 SQL 查询都是通过 Doctrine\DBAL\Connection 触发的。
use SimpleORM\Repository; use Doctrine\DBAL\DriverManager; DriverManager::getConnection([ 'driver' => 'pdo_sqlite', 'path' => 'database.sqlite', ]); $books = new Repository(Book::class, $connection);
检索信息
用所有元素填充您的 Repository。
$books->all(); foreach($books as $book) { // do something here }