Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

php - DDD - persisting aggregate children only if changed

I'm trying use DDD in an application I'm currently working on. I have a following UserAggregate structure:

UserAggregate
- ProfileEntity
- ImageEntity
- RatingEntity

And i have a UserRepository which is querying entities mappers to build a UserAggregate.

Now I'd like to pass the UserAggregate to the UserRepository for persistance, like UserRepository->save(UserAggregate). How do I tell the UserRepository that UserAggregate children entities have changed and needs to be saved? Is there any common pattern for that? I'm aware of UintOfWork pattern but can't really imagine how it may help with children, as I'd like to hit the mappers (and the database) only if the children entities are actually changed.

Is there any way to track a "dirty state" of the entity object, specifically in PHP? Or Am I missed the concept of aggregate roots and repositories?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are basically two approaches to that problem. You can either use snapshot comparison or proxy-based change tracking. Both of them have advantages and disadvantages. Selection also depends on the libraries you use, as they may have support for one of them.

Here, I describe the basic approaches. I don't know what libraries you're using exactly, so this will help you select a strategy and evaluate libraries.

Basic Design Considerations

Both strategies are a responsibility of the persistence mechanism and MUST NOT leak into the domain and application logic. In other words, they must be transparent to the users of the repository and to domain objects.

Snapshot Comparison

With this strategy, you keep a snapshot of the aggregate data when the aggregate is loaded through the repository. Later, when the potentially modified aggregate is passed in an Update call to the repository again, you walk the aggregate to determine whether data in it changed or not.

Proxy-based Change Tracking

With this strategy, you return an object that proxies the real aggregate instead of the aggregate itself. The proxy is created and used to wrap the aggregate when the aggregate is loaded through the repository.

The proxy does nothing on read operations on the aggregate, but sets a dirty flag whenever a mutating operation is invoked. When the (proxied) aggregate is passed to the repository for persisting, you simply check the dirty flag.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...