نمط Event Sourcing يحفظ كل تغيير كحدث بدلاً من الحالة النهائية، مما يتيح إعادة بناء الحالة في أي وقت.
// تعريف حدث
Class MyApp.Events.BaseEvent Extends %Persistent {
Property AggregateId As %Integer;
Property EventType As %String;
Property EventData As %DynamicObject;
Property Timestamp As %TimeStamp;
Property UserId As %String;
Index AggregateIdx On AggregateId;
}
// تسجيل حدث
ClassMethod RegisterEvent(aggregateId, type, data) {
Set event = ##class(MyApp.Events.BaseEvent).%New()
Set event.AggregateId = aggregateId
Set event.EventType = type
Set event.EventData = data
Set event.Timestamp = $ZDT($H, 3)
Do event.%Save()
// تحديث الإسقاط (Projection)
Do ..UpdateProjection(aggregateId)
}
// إعادة بناء الحالة من الأحداث
ClassMethod RebuildState(aggregateId) As %DynamicObject {
Set state = {}
&sql(SELECT EventType, EventData INTO :type, :data
FROM MyApp.Events.BaseEvent
WHERE AggregateId = :aggregateId
ORDER BY Timestamp)
While SQLCODE = 0 {
// تطبيق الحدث على الحالة
Set state = ..ApplyEvent(state, type, data)
&sql(FETCH MyApp.Events.BaseEvent INTO :type, :data)
}
Return state
}