2015-03-11 21:42
浏览 244


I am developing a "fat model" for my open-source project, and I am working on the layer that will sit between the ORM (RedBeanPHP) and the controller.

I will have a User class, and probably a UserFactory/UserMapper class that can construct User objects, as well as perform meta-actions like usernameExists, etc.

A number of other SO questions/blog posts have pointed out that if I need to retrieve a collection of User objects, it would be inefficient to have my UserMapper class iterate through through the result set and build n User objects.

My idea then, is to create a UserCollection class which implements PHP's ArrayObject class. UserMapper would be able to create a UserCollection that stores the raw result set internally, as a multidimensional array. I could then implement ArrayObject's iterator functions, [], etc to construct the corresponding User objects on demand.

Is this a smart way to do it? What do I need to consider before taking this approach?

图片转代码服务由CSDN问答提供 功能建议


我将有一个 User 类,可能还有 UserFactory / UserMapper 类,它可以构造 User 对象 ,以及执行 usernameExists 等元操作。

许多其他SO问题/博客帖子指出,如果我需要检索一个 User 对象的集合,让我的 UserMapper 类遍历结果集并构建 n 用户对象。

我的想法是创建一个 UserCollection 类,它实现了PHP的 ArrayObject 类。 UserMapper 将能够创建一个 UserCollection ,它将内部的原始结果集存储为多维数组。 然后我可以实现 ArrayObject 的迭代器函数, [] 等来按需构造相应的 User 对象。

这是一种聪明的方法吗? 在采用这种方法之前我需要考虑什么?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douliangbian7323 2015-03-12 00:36

    It would appear that this is exactly how Laravel's ORM, Eloquent, does it:

    class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable {
    public function fetch($key)
    return new static(array_fetch($this->items, $key));

    If the most popular PHP framework is doing it that way, I'd say it's a pretty good endorsement.

    打赏 评论
  • doubo7131 2015-03-11 21:50

    To render big lists of data, it will in fact be slower using an instance per row. That's where the flyweight pattern comes in handy...

    打赏 评论

相关推荐 更多相似问题