实体常量

Testing Is Documentation

tests/Database/Ddd/EntityDefineTest.php实体常量 - 图1

实体初始化会校验一些必须定义的常量 const,这是实体对应的数据库表的一些映射,这简化了 ORM 底层后续处理逻辑。

Uses

  1. <?php
  2. use Leevel\Database\Ddd\Entity;
  3. use Leevel\Database\Ddd\GetterSetter;
  4. use Tests\Database\DatabaseTestCase as TestCase;
  5. use Tests\Database\Ddd\Entity\DemoEntity;

基本常量

基础常量

常量 TABLE,ID,AUTOSTRUCT 是每一个实体必须要定义的,否则会抛出异常。

  • TABLE 数据库表名,例如 test
  • ID 主键字段,例如 null,id['id1', 'id2']
  • AUTO 自增字段,例如 nullid
  • STRUCT 数据库字段 ['id' => [self::READONLY => true], 'name' => []]

测试模型

  1. namespace Tests\Database\Ddd\Entity;
  2. use Leevel\Database\Ddd\Entity;
  3. use Leevel\Database\Ddd\GetterSetter;
  4. class DemoEntity extends Entity
  5. {
  6. use GetterSetter;
  7. const TABLE = 'test';
  8. const ID = 'id';
  9. const AUTO = 'id';
  10. const STRUCT = [
  11. 'id' => [
  12. self::READONLY => true,
  13. ],
  14. 'name' => [],
  15. ];
  16. }
  17. ``
  18. ``` php
  19. public function testBaseUse(): void
  20. {
  21. $entity = new DemoEntity();
  22. $this->assertInstanceof(Entity::class, $entity);
  23. $this->assertSame(DemoEntity::STRUCT, $entity->fields());
  24. $this->assertSame(DemoEntity::TABLE, $entity->table());
  25. $this->assertSame(DemoEntity::ID, $entity->primaryKey());
  26. $this->assertSame(DemoEntity::AUTO, $entity->autoIncrement());
  27. }

基本常量未定义将会抛出异常

测试模型

  1. namespace Tests\Database\Ddd;
  2. class Test1Entity extends Entity
  3. {
  4. use GetterSetter;
  5. }
  1. public function testConstDefined(): void
  2. {
  3. $this->expectException(\InvalidArgumentException::class);
  4. $this->expectExceptionMessage('The entity const TABLE was not defined.');
  5. $entity = new Test1Entity();
  6. }