首页 理论 架构 工程 文档 白皮书 著作 研究 案例 下载 博客 关于 开始使用 →

第171章 ObjectService

第171章 ObjectService

171.1 提出背景

在第167章中,ICAI已经建立了Object的组合体系。

Object不是一个普通的数据记录,而是ICAI用于描述、识别、管理和关联现实对象或系统内部对象的基本领域对象。

其基本模型为:

O=(ID,T,A,S,R)O=(ID,T,A,S,R)

其中:

  • OO:Object;
  • IDID:Object Identity,对象身份;
  • TT:Object Type,对象类型;
  • AA:Attributes,对象属性;
  • SS:State,对象状态;
  • RR:Relations,对象关系。

第169章进一步建立了Service层,第170章则通过IndividualService完成了Individual领域对象的Service化管理。

因此,本章建立:

ObjectService(对象服务)

ObjectService负责Object的完整管理生命周期:

对象管理
 ↓
对象创建
 ↓
对象读取
 ↓
对象更新
 ↓
对象删除

其核心模型为:

ObjectService=Manage+Create+Read+Update+DeleteObjectService = Manage + Create + Read + Update + Delete

ObjectService解决的问题是:

如何让ICAI中的Object成为一个能够被创建、识别、读取、修改、关联和删除的实际领域对象。


171.2 ObjectService定义

ObjectService 是负责Object领域对象生命周期和对象关系管理的应用服务。

可以定义:

OS=(O,I,A,S,R,P,L)OS=(O,I,A,S,R,P,L)

其中:

  • OO:Object;
  • II:Identity;
  • AA:Attribute;
  • SS:State;
  • RR:Relation;
  • PP:Persistence;
  • LL:Lifecycle。

ObjectService并不取代Object。

Object仍然是Domain Object:

Object
    ├── Identity
    ├── Type
    ├── Attributes
    ├── State
    └── Relations

ObjectService负责:

Create
Read
Update
Delete
Manage

因此:

Object=Domain ObjectObject = Domain\ Object

而:

ObjectService=Object Lifecycle ServiceObjectService = Object\ Lifecycle\ Service


171.3 对象管理

171.3.1 对象管理定义

对象管理(Object Management) 是对Object从创建到删除整个生命周期进行组织、协调和控制的过程。

可以表示为:

Management(O)=Identity+Lifecycle+Attribute+State+RelationManagement(O) = Identity + Lifecycle + Attribute + State + Relation

因此ObjectService并不是简单的CRUD封装。

CRUD只是ObjectService的基础操作:

Create
Read
Update
Delete

完整Object Management还包括:

Identity管理
Type管理
Attribute管理
State管理
Relation管理
Lifecycle管理
Persistence管理

171.4 Object的身份管理

每一个Object必须具有稳定的Identity。

可以定义:

Identity=(ID,Type)Identity=(ID,Type)

例如:

Object ID = 2001
Type = device

或者:

Object ID = 2002
Type = vehicle

Identity用于区分具体对象。

因此:

Object A
ID = 2001

Object B
ID = 2002

即使两个Object的Type完全相同,也仍然是两个不同对象。

因此:

IDA≠IDBID_A \neq ID_B

表示两个Object具有不同身份。


171.5 Object类型

Object的Type用于表示对象属于什么类型。

例如:

device
vehicle
product
document
location
component
tool
resource

Type与Individual的Type类似,但两者概念不能混淆。

Individual表示:

具有自身认知结构和运行状态的个体主体。

Object表示:

被系统识别、描述、组合、关联和操作的对象。

例如:

Individual
   ↓
Robot
   ↓
Object
   ├── Arm
   ├── Wheel
   └── Sensor

Robot可以是Individual,而Arm、Wheel、Sensor可以作为Object被Robot组合。

因此:

Individual≠ObjectIndividual \neq Object

但:

Individual→ObjectIndividual \rightarrow Object

可以形成组合关系。


171.6 对象创建

171.6.1 创建定义

Object创建是建立一个具有唯一Identity、Type、初始Attribute和初始State的Domain Object过程。

可以定义:

Create(O)=Identity+Type+Attribute+InitialStateCreate(O) = Identity + Type + Attribute + InitialState

基本流程:

Input
 ↓
Validate
 ↓
Create Object
 ↓
Assign Identity
 ↓
Set Type
 ↓
Set Attributes
 ↓
Set Initial State
 ↓
Persist
 ↓
Created

例如:

$input = array(
    'type' => 'device',
    'name' => 'Sensor-001'
);

ObjectService接收输入后建立Object。


171.7 Object创建的PHP实现

基础Object:

class ObjectEntity
{
    protected $id;
    protected $type;
    protected $attributes;
    protected $state;

    public function __construct($id, $type)
    {
        $this->id = $id;
        $this->type = $type;
        $this->attributes = array();
        $this->state = 'created';
    }

    public function getId()
    {
        return $this->id;
    }

    public function getType()
    {
        return $this->type;
    }

    public function setState($state)
    {
        $this->state = $state;
    }

    public function getState()
    {
        return $this->state;
    }
}

ObjectService:

class ObjectService
{
    protected $repository;

    public function __construct($repository)
    {
        $this->repository = $repository;
    }

    public function create($input)
    {
        if (empty($input['type'])) {
            return false;
        }

        $object = new ObjectEntity(
            null,
            $input['type']
        );

        $object->setState('created');

        return $this->repository->save(
            $object
        );
    }
}

这里需要特别注意:

ObjectService

负责创建过程。

而:

ObjectEntity

负责Object自身的数据和领域状态。


171.8 对象读取

Object读取可以分为两个层次。

第一层是:

读取Object基本数据

第二层是:

恢复Object完整结构

因此:

Read(O)=Persistence Load+Domain Reconstruction+Composition Load+Relation LoadRead(O) = Persistence\ Load + Domain\ Reconstruction + Composition\ Load + Relation\ Load

基本流程:

Object ID
 ↓
ObjectRepository
 ↓
Object Record
 ↓
Object Domain Object
 ↓
Load Attributes
 ↓
Load State
 ↓
Load Relations
 ↓
Runtime Object

171.9 Object读取与组合体系

第167章已经定义:

Object
 ↓
Attribute

以及:

Composite Object
 ↓
Object
 ↓
Attribute

因此读取一个Composite Object时,不能只读取主Object。

例如:

Car
 ├── Engine
 ├── Wheel
 ├── Door
 └── Seat

如果读取Car:

ObjectService
      ↓
Car
      ↓
Engine
Wheel
Door
Seat

则需要进一步读取Object Relation。

因此:

Read(Composite Object)=Read(Main Object)+Read(Child Objects)+Read(Relations)Read(Composite\ Object) = Read(Main\ Object) + Read(Child\ Objects) + Read(Relations)


171.10 对象属性读取

Object的Attribute是独立的领域结构。

第167章定义:

A=(N,V,T,S,Time)A=(N,V,T,S,Time)

其中:

  • NN:Name;
  • VV:Value;
  • TT:Type;
  • SS:State;
  • TimeTime:时间信息。

因此ObjectService读取Object后,可以进一步加载:

Object
 ↓
Attribute[]

例如:

Device
 ├── name = Sensor-001
 ├── voltage = 12V
 ├── status = active
 └── location = Room-A

ObjectService负责组织读取过程,但Attribute自身仍然属于Domain Object体系。


171.11 对象更新

171.11.1 更新定义

Object更新是对已经存在的Object的合法信息、属性、状态或关系进行修改。

可以定义:

Update(O)=Attribute+State+RelationUpdate(O) = Attribute + State + Relation

但不同类型的更新必须保持职责边界。

例如:

Attribute更新
State更新
Relation更新

不能简单地全部作为普通数据库字段更新。


171.12 Object属性更新

例如:

$object->setAttribute(
    'location',
    'Room-B'
);

ObjectService负责协调:

Request
 ↓
ObjectService
 ↓
Load Object
 ↓
Update Attribute
 ↓
Validate
 ↓
Repository
 ↓
Save

例如:

public function updateAttribute(
    $objectId,
    $name,
    $value
) {
    $object = $this->get($objectId);

    if (!$object) {
        return false;
    }

    $object->setAttribute(
        $name,
        $value
    );

    return $this->repository->save(
        $object
    );
}

171.13 Object状态更新

Object也具有自身State。

例如:

created
ready
active
inactive
blocked
failed
archived

状态变化应该通过规则控制。

例如:

created
 ↓
ready
 ↓
active

异常:

active
 ↓
failed

停用:

active
 ↓
inactive

因此:

Statet+1=Transition(Statet,Event,Condition)State_{t+1} = Transition(State_t,Event,Condition)

ObjectService可以负责调用State Engine,而不是直接允许任何状态任意跳转。


171.14 Object关系更新

Object不仅具有属性,还可能具有关系。

例如:

Car
 ↓
contains
 ↓
Engine

或者:

Robot
 ↓
has
 ↓
Arm

或者:

Product
 ↓
belongs_to
 ↓
Category

Object Relation可以定义:

R=(O1,T,O2,C,S)R=(O_1,T,O_2,C,S)

其中:

  • O1O_1:对象A;
  • TT:关系类型;
  • O2O_2:对象B;
  • CC:关系条件;
  • SS:关系状态。

ObjectService可以提供:

addRelation()
removeRelation()
getRelations()

但具体Relation结构仍然属于Relation Domain Object。


171.15 对象删除

171.15.1 删除定义

Object删除是从系统当前有效对象集合中移除一个Object。

但“删除”并不只有一种形式。

必须区分:

Physical Delete
Logical Delete
Archive

171.16 物理删除

物理删除意味着Object记录真正从Persistence中移除。

例如:

DELETE FROM objects
WHERE id = 2001

但物理删除存在风险。

如果Object已经被:

Individual
Memory
Experience
Relation
History
Behavior
Action

引用,则直接删除可能造成关系断裂。

因此ObjectService不能简单执行:

delete($id)

就立即删除。


171.17 逻辑删除

逻辑删除可以使用:

state = deleted

或者:

deleted_at != NULL

Object仍然存在于Persistence中,但不再作为Active Object参与正常运行。

例如:

active
 ↓
inactive
 ↓
deleted

这样可以保留历史关系。

因此对于ICAI系统而言,在存在大量历史引用时:

Logical Delete>Physical DeleteLogical\ Delete > Physical\ Delete

通常更加安全。

但这不是绝对规则。

是否物理删除,应根据Object类型、关系数量、历史要求和数据保留规则决定。


171.18 对象归档

对于不再使用但需要保留的Object,可以进入:

archived

例如:

active
 ↓
inactive
 ↓
archived

Archived Object仍然可以被读取历史记录,但通常不再参与当前运行流程。

因此:

Deleted

与:

Archived

不是完全相同的状态。

可以定义:

Archived=Retained+InactiveArchived = Retained + Inactive

而:

Deleted=No Longer ActiveDeleted = No\ Longer\ Active

具体是否保留Persistence记录,则由系统策略决定。


171.19 删除前检查

ObjectService执行删除前,应检查:

Object是否存在
 ↓
是否允许删除
 ↓
是否存在重要Relation
 ↓
是否存在Active引用
 ↓
是否存在运行任务
 ↓
删除方式

例如:

public function delete($id)
{
    $object = $this->get($id);

    if (!$object) {
        return false;
    }

    if ($object->getState() == 'active') {
        return false;
    }

    return $this->repository->delete(
        $id
    );
}

更完整的工程实现应该由专门规则或DeletePolicy判断:

ObjectService
      ↓
DeletePolicy
      ↓
Relation Check
      ↓
State Check
      ↓
Reference Check
      ↓
Delete / Archive

171.20 ObjectService与ObjectRepository

ObjectService不直接执行SQL。

应建立:

ObjectRepository

负责:

find()
findByType()
save()
delete()
exists()

例如:

class ObjectRepository
{
    public function find($id)
    {
        // Load object from MySQL
    }

    public function save($object)
    {
        // Insert or update
    }

    public function delete($id)
    {
        // Delete object
    }
}

ObjectService:

class ObjectService
{
    protected $repository;

    public function __construct(
        $repository
    ) {
        $this->repository = $repository;
    }

    public function get($id)
    {
        return $this->repository->find($id);
    }
}

因此:

ObjectService→ObjectRepository→MySQLObjectService \rightarrow ObjectRepository \rightarrow MySQL


171.21 ObjectService与Engine

ObjectService本身不应该承担复杂计算。

例如:

ObjectService
       ↓
ObjectStateEngine

负责状态转换:

Current State
+
Event
+
Condition
↓
New State

又例如:

ObjectService
       ↓
ObjectRelationEngine

负责关系合法性判断。

因此:

Service=ProcessService = Process Engine=Computation/RuleEngine = Computation/Rule

这与第169章建立的Service层原则保持一致。


171.22 ObjectService与IndividualService

IndividualService与ObjectService具有相似结构,但管理对象不同。

IndividualService
        ↓
Individual
ObjectService
        ↓
Object

二者又可以形成组合:

Individual
    ↓
Object[]

例如:

Robot
    ↓
ObjectService
    ├── Arm
    ├── Wheel
    ├── Sensor
    └── Battery

因此:

IndividualService→Individual→ObjectService→ObjectIndividualService \rightarrow Individual \rightarrow ObjectService \rightarrow Object

但不意味着Object一定属于某个Individual。

Object也可以独立存在。

例如:

Product
Location
Document
Resource

都可以成为独立Object。


171.23 ObjectService与Attribute

Attribute不应直接等同于Object。

前面已经建立:

Object→AttributeObject \rightarrow Attribute

例如:

Device
 ├── voltage
 ├── weight
 └── location

这里:

Device = Object
voltage = Attribute
weight = Attribute
location = Attribute

ObjectService负责管理Object。

AttributeService可以进一步负责Attribute的独立生命周期。

因此:

ObjectService
      ↓
Object
      ↓
Attribute

当Attribute复杂到具有独立Identity、State、Relation时,它也可以进一步提升为独立Object。

这形成前面第167章建立的:

Attribute→Object→Composite ObjectAttribute \rightarrow Object \rightarrow Composite\ Object

结构演化。


171.24 Object管理生命周期

ObjectService需要建立明确生命周期:

Created→Initialized→Ready→Active→Updated→Inactive→ArchivedCreated \rightarrow Initialized \rightarrow Ready \rightarrow Active \rightarrow Updated \rightarrow Inactive \rightarrow Archived

删除路径:

Inactive→DeletedInactive \rightarrow Deleted

异常:

Active→Failed→InactiveActive \rightarrow Failed \rightarrow Inactive

因此:

Created
   ↓
Initialized
   ↓
Ready
   ↓
Active
   ↓
Updated
   ↓
Inactive
   ↓
Archived

不是所有Object都必须经历全部状态。

例如一个临时Object可能:

Created
 ↓
Ready
 ↓
Deleted

因此生命周期必须允许根据Object类型和业务规则产生不同路径。


171.25 ObjectService PHP基础结构

可以建立如下基础Service:

class ObjectService
{
    protected $repository;
    protected $stateEngine;

    public function __construct(
        $repository,
        $stateEngine
    ) {
        $this->repository = $repository;
        $this->stateEngine = $stateEngine;
    }

    public function create($input)
    {
        if (empty($input['type'])) {
            return false;
        }

        $object = new ObjectEntity(
            null,
            $input['type']
        );

        $object->setState('created');

        return $this->repository->save(
            $object
        );
    }

    public function get($id)
    {
        return $this->repository->find(
            $id
        );
    }

    public function update($object)
    {
        if (!$object) {
            return false;
        }

        return $this->repository->save(
            $object
        );
    }

    public function delete($id)
    {
        $object = $this->get($id);

        if (!$object) {
            return false;
        }

        if ($object->getState() == 'active') {
            return false;
        }

        return $this->repository->delete(
            $id
        );
    }

    public function changeState(
        $id,
        $newState
    ) {
        $object = $this->get($id);

        if (!$object) {
            return false;
        }

        $currentState =
            $object->getState();

        if (!$this->stateEngine->canTransition(
            $currentState,
            $newState
        )) {
            return false;
        }

        $object->setState(
            $newState
        );

        return $this->update(
            $object
        );
    }
}

这个结构体现:

ObjectService
 ├── Create
 ├── Read
 ├── Update
 ├── Delete
 └── State

而Repository和StateEngine保持独立。


171.26 Object数据库结构

可以建立基础:

objects

id
type
name
state
created_at
updated_at

属性:

object_attributes

id
object_id
name
value
type
state
created_at
updated_at

关系:

object_relations

id
object_id
relation_type
target_object_id
state
created_at

状态历史:

object_state_history

id
object_id
from_state
to_state
reason
created_at

这样可以将:

Object
Attribute
Relation
State
State History

分别持久化。

数据库结构对应的是Persistence层,并不等于ICAI Domain Object本身。


171.27 Object删除与关系保护

Object删除是ObjectService中必须特别谨慎处理的操作。

例如:

Robot
 ↓
contains
 ↓
Arm

如果直接删除Arm:

Robot
 ↓
contains
 ↓
NULL

就会造成关系断裂。

因此删除流程应该考虑:

Delete(O)=Existence+State+Reference+Relation+PolicyDelete(O) = Existence + State + Reference + Relation + Policy

完整过程:

Delete Request
 ↓
Object Exists?
 ↓
Current State?
 ↓
Referenced?
 ↓
Has Important Relations?
 ↓
Delete Policy
 ↓
Logical Delete / Archive / Physical Delete

因此ObjectService不是简单执行:

DELETE

而是负责整个删除过程的合法性组织。


171.28 ObjectService的统一CRUD模型

ObjectService最基础的四个操作为:

CRUD=Create+Read+Update+DeleteCRUD = Create + Read + Update + Delete

但是在ICAI中应进一步扩展为:

ObjectManagement=CRUD+State+Attribute+Relation+LifecycleObjectManagement = CRUD + State + Attribute + Relation + Lifecycle

因此最终模型:

Create
 ↓
Read
 ↓
Update
 ↓
State
 ↓
Relation
 ↓
Lifecycle
 ↓
Delete / Archive

CRUD只是基础层。

Object Management才是完整的ICAI对象管理层。


171.29 ObjectService与Runtime Object

第168章已经定义:

RuntimeObject=(Object,State,Context,Relation,Time)RuntimeObject=(Object,State,Context,Relation,Time)

因此ObjectService读取Object之后,还可能进一步将它加载到Runtime环境。

过程:

MySQL
 ↓
ObjectRepository
 ↓
Object
 ↓
Attributes
 ↓
Relations
 ↓
State
 ↓
Runtime Object

因此:

Persistence Object→Domain Object→Runtime ObjectPersistence\ Object \rightarrow Domain\ Object \rightarrow Runtime\ Object

ObjectService是这一过程的重要应用服务入口。


171.30 ObjectService在ICAI中的位置

结合前面的架构:

Controller
      ↓
Service
      ↓
Domain Object
      ↓
Engine
      ↓
Repository
      ↓
MySQL

具体到Object:

Controller
      ↓
ObjectService
      ├── ObjectRepository
      ├── ObjectStateEngine
      └── ObjectRelationEngine
              ↓
          Object
          ├── Attribute
          ├── State
          └── Relation

如果Object属于Individual:

IndividualService
        ↓
Individual
        ↓
ObjectService
        ↓
Object

这样便形成了Individual与Object之间的工程连接。


171.31 ObjectService完整生命周期模型

可以将整个Object生命周期统一表示为:

OL=Create→Initialize→Read→Ready→Active→Update→Inactive→Archive/DeleteO_L= Create \rightarrow Initialize \rightarrow Read \rightarrow Ready \rightarrow Active \rightarrow Update \rightarrow Inactive \rightarrow Archive/Delete

具体过程:

Create Object
      ↓
Assign Identity
      ↓
Set Type
      ↓
Load Attributes
      ↓
Set State
      ↓
Save
      ↓
Read
      ↓
Active
      ↓
Update
      ↓
State Change
      ↓
Inactive
      ↓
Archive / Delete

171.32 本章核心原则

ObjectService必须遵循以下原则。

第一,Object是Domain Object

ObjectService不能取代Object。

第二,Service负责流程

Service负责:

Create
Read
Update
Delete

以及对象生命周期协调。

第三,Repository负责Persistence

Service不直接承担SQL。

第四,Engine负责规则和计算

状态转换、关系合法性等复杂规则由Engine负责。

第五,State必须真实

不能为了程序方便直接把Object设置成任意状态。

第六,Delete必须受保护

必须检查引用、关系、状态和删除策略。

第七,数据库不是对象本身

MySQL记录是Persistence。

Object是Domain Object。

Runtime Object是运行时实例。

三者必须保持边界。


171.33 ObjectService统一模型

最终可以建立:

OS=(C,R,U,D,M,S,Rl,L)\boxed{ OS=(C,R,U,D,M,S,Rl,L) }

其中:

  • CC:Create;
  • RR:Read;
  • UU:Update;
  • DD:Delete;
  • MM:Management;
  • SS:State;
  • RlRl:Relation;
  • LL:Lifecycle。

基本流程:

Create→Read→Update→State→Relation→Archive/DeleteCreate \rightarrow Read \rightarrow Update \rightarrow State \rightarrow Relation \rightarrow Archive/Delete

其工程结构:

ObjectService→Object→Engine→Repository→MySQL\boxed{ ObjectService \rightarrow Object \rightarrow Engine \rightarrow Repository \rightarrow MySQL }

而在ICAI完整运行体系中:

Individual→Object→Attribute→State→Relation→Knowledge→Capability→Method→Behavior\boxed{ Individual \rightarrow Object \rightarrow Attribute \rightarrow State \rightarrow Relation \rightarrow Knowledge \rightarrow Capability \rightarrow Method \rightarrow Behavior }

ObjectService因此成为连接 Individual组合体系、Object领域体系、Runtime体系和Persistence体系 的基础Service之一。


171.34 本章小结

第171章完成了Object从理论对象到工程服务对象的进一步落地。

Object定义:

O=(ID,T,A,S,R)O=(ID,T,A,S,R)

ObjectService定义:

OS=(C,R,U,D,M,S,Rl,L)OS=(C,R,U,D,M,S,Rl,L)

二者关系为:

Object
    ↓
Domain Object

ObjectService
    ↓
Lifecycle / Process Management

完整工程流程为:

Create
 ↓
Identity
 ↓
Type
 ↓
Attribute
 ↓
State
 ↓
Relation
 ↓
Read
 ↓
Update
 ↓
Inactive
 ↓
Archive / Delete

最终形成:

ObjectService=Object Lifecycle+CRUD+State+Relation+Persistence Coordination\boxed{ ObjectService = Object\ Lifecycle + CRUD + State + Relation + Persistence\ Coordination }

由此,第170章的IndividualService与第171章的ObjectService形成了两个基础领域Service:

IndividualService
        ↓
Individual

ObjectService
        ↓
Object

同时:

Individual
   ↓
Composition
   ↓
Object[]
   ↓
Attribute[]
   ↓
Relation[]

开始形成可以直接映射到PHP OOP、MVC、Repository、MySQL和Runtime的完整对象管理基础。

下一阶段,Service层可以继续从基础对象管理进入 AttributeService、CapabilityService、MethodService 等专业领域服务,使第167章建立的Object Composition逐步转化为真正可执行的ICAI软件工程体系。

Leave a Reply

Your email address will not be published. Required fields are marked *