重构 第二次重写了 Datamappify

fredwu · 2013年04月11日 · 最后由 fredwu 回复于 2013年06月17日 · 3316 次阅读

Datamappify: https://github.com/fredwu/datamappify

Compose and manage domain logic and data persistence separately and intelligently, Datamappify is loosely based on the Repository Pattern and Entity Aggregation.

Datamappify is built using Virtus and existing ORMs (ActiveRecord and Sequel, etc). The design goal is to utilise the powerfulness of existing ORMs as well as to separate domain logic (model behaviour) from data persistence.

第一次重写增添了很多功能,比如 Entity 支持多重 ORM。

这次通过与牛人朋友的讨论与取经,又进行了第二次的重写。整个代码的架构又提升了一个档次,嘿嘿~ :P

还有许多功能要陆续添加——

  • Track dirty entity attributes.
  • Attribute lazy-loading.
  • Hooks for persistence (before_save and after_save, etc).
  • Authoritative source.
  • Enforce attribute type casting.
  • Support for configurable primary keys and foreign keys.

欢迎大家来提供反馈。:)

1 楼 已删除

有几个问题:

  • 核心思想是是实现贫血模型?
  • entity 和 orm 的 model 的关系?
  • 为啥要显式声明字段?

#2 楼 @jasl Orz... 搜索了半天才找到贫血模型是什么…… 好奇葩的名字…… 嗯,Datamappify 的核心思想不仅仅是 domain logic 与 data persistence 的隔离而已,还有 aggregation —— 从不同的 data store 里提取数据。

ORM 的 model 目前位置仅仅用于数据的 CRUD。

声明字段是 type casting 吗?目前 Datamappify 还没有加入 type casting 的支持,但是以后会。Type casting 用来作为 attribute 的 validation 的手段之一。

@fredwu 代码看完了,精简了很多。看来最重要的概念是aggregation 。这对公司现有的多个数据源上做应用很有帮助。

楼主你好,我有个问题想咨询一下

在 Repository 的介绍里面看到这样的代码

map_attribute :last_name,      'ActiveRecord::User#surname'
map_attribute :driver_license, 'ActiveRecord::UserDriverLicense#number'
map_attribute :passport,       'Sequel::UserPassport#number'
map_attribute :health_care,    'Sequel::UserHealthCare#number'

在这里看到同时支持了ActiveRecordSequel,这意思是说同一个 Repository 中的数据能支持多个数据源的意思么

#6 楼 @ywjno

这意思是说同一个 Repository 中的数据能支持多个数据源的意思么

对的!

说一点不成熟看法,我觉得 model 不用列出属性比较好,自动与 db 同步,这样符合 DRY 原则。

太高深了看不懂啊

#3 楼 @fredwu 不是,google 第一个还可以啊!

对领域方面的东西不是很了解

@fredwu 挺酷的东西,给几个建议。

  1. 能不能支持下 ActiveRecord 3.2.13 啊,想用,,用不了。

  2. UserRepository 的 map_attribute 会动态生成 ActiveRecord::User?老项目已经有 ActiveRecord 的 model 了怎么办。

  3. 目标是跨不同的数据源 设计 model?同一个数据源里其实也有很多这种场景啊,比如 step by step 的用户体验。跨表的 Lazy 也会很实用。

  4. 对已经有的模型不知道怎么改。可以如下吗?

class User < ActiveRecord::Base

end

class UserReponsitory
  include Datamappify::Repository

  for_entity UserEntity
  map_attribute "ActiveRecord::User#surname'
end

class UserEntity
  include Datamappify::Entity

end
  1. 在你的测试里 AdminUser 的 level 字段 保存的时候会去哪?

#13 楼 @yakjuly

  1. 因为我们团队目前在用 Datamappify + Rails 4.0 开发,所以暂时没有机会加入 3.2 版本的支持。不过我猜想应该不难,如果有兴趣的话你可以提交个 PR。:)

  2. 如果已经有 ActiveRecord model 了的话,Datamappify 会自动用现有的,不会再生成。

  3. 是的,目前为止我们就是这么用的。特别是,配合 simple_form 使用,可以减少很多 nested attributes 的使用。

  4. 对的。

  5. level 会被保存在 users 表中,因为 entity 的继承是 STI (Single Table Inheritance) 。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号