enoffspb / entity-manager
dev-main
2021-11-25 12:49 UTC
Requires (Dev)
- phpstan/phpstan: ^0.12.96
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-25 19:20:11 UTC
README
! WORK IN PROGRESS !
EntityManager 是一个 PHP 库,用作一个简单、独立的数据持久层,用于处理没有与持久层关联的微小实体。它对于面向对象分析(OOAD)很有用,可以区分问题域和技术域。
实现了以下驱动程序:MySql、PostgreSql、InMemory(用于自动测试);
使用 EntityManager 的公共接口
namespace EnoffSpb\EntityManager\Interfaces; interface EntityManagerInterface { public function save(object $entity): bool; public function update(object $entity): bool; public function delete(object $entity): bool; public function getRepository(string $entityClass): RepositoryInterface; public function getDriver(): DriverInterface; } interface RepositoryInterface { public function getById($id): ?object; public function getList(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array; }
使用概述
$entityManager = new EntityManager(/** pass the params */); /** Configure $entityManager as described later */ $myEntity = new MyEntity(); // Any custom class $myEntity->name = 'name'; $myEntity->setAnotherField('value'); $entityManager->save($myEntity); // save an entity // If MyEntity has auto-generated primary key it will be available in PK field after saving $entityId = $myEntity->getId(); // or $myEntity->id or $myEntity->customPk or otherwise else depends on an configuration $myEntity->name = 'New name'; $entityManager->update($myEntity); // update an exists entity $entityManager->delete($myEntity); // delete an exists entity // using Repository $repository = $entityManager->getRepository(MyEntity::class); $existsEntity = $repository->getById(1); $list = $repository->getList([ 'name' => 'search value' ]); foreach($list as $entity) { // $entity is an instance of MyEntity }
创建 EntityManager 实例
创建一个驱动程序和一个实体配置,并将其传递给 EntityManager。
use EnoffSpb\EntityManager\EntityManager; use EnoffSpb\EntityManager\Driver\MySql\MysqlDriver; // Create a driver for DB, e.g. MySqlDriver $driver = new MySqlDriver($dsn = 'mysql:host=localhost;dbname=db', $user = 'user', $password = 'pwd'); // Describe an entities config (see full format below) $entitiesConfig = [ MyEntity::class => [/** config is here */], AnotherEntity::class => [] ]; // Create an instance of EntityManager $entityManager = new EntityManager($driver, $entitiesConfig);
实体配置
$entitiesConfig = [ MyEntity::class => [ 'primaryKey' => 'id', // by default 'tableName' => 'table_name', 'repositoryClass' => MyEntityRepository::class, 'mapping' => [ // a list of columns 'columnName' => [ 'attribute' => 'attrName', 'getter' => 'getterName', 'setter' => 'setterName', 'type' => Column::TYPE_VARCHAR, 'length' => '', 'nullable' => '', ], // another columns are here ] ], AnotherEntity::class => [ /* An AnotherEntity config is here */ ] ];