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

使用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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等