douyi0219 2015-03-11 21:42
浏览 255
已采纳

使用PHP的ArrayObject实现模型对象的集合

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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决