【问题标题】:Using PHP's ArrayObject to implement a collection of model objects使用 PHP 的 ArrayObject 实现模型对象的集合
【发布时间】:2015-03-11 21:42:16
【问题描述】:

我正在为我的open-source project 开发一个“胖模型”,并且我正在研究位于 ORM (RedBeanPHP) 和控制器之间的层。

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

许多其他 SO 问题/博客文章指出,如果我需要检索 User 对象的 集合,让我的 UserMapper 类遍历将是低效的结果集并构建 n User 对象。

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

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

【问题讨论】:

    标签: php model-view-controller datamapper redbean arrayobject


    【解决方案1】:

    要渲染大数据列表,实际上每行使用一个实例会更慢。这就是享元模式派上用场的地方...... http://sourcemaking.com/design_patterns/Flyweight/php

    【讨论】:

    • 我不确定这有多相关,因为我希望 User 对象的共同数据相对较少。
    【解决方案2】:

    看来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));
    }
    
    }
    

    如果最流行的 PHP 框架是这样做的,我会说这是一个很好的认可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2013-04-18
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多