php – 实例化对象列表的正确方法

我一直想知道我应该如何编写,以及使用哪种设计模式来创建对象列表.

首先,考虑我有一个Customer类和一个Order类.
我想获得属于用户的所有订单.

我想要$oCustomer-> getOrders();返回Order对象数组.

基本上,我一直在考虑:

OrderManager类,它是一个单例,能够从存储引擎检索Order数据并构建Order对象.但我一直在阅读这是一个不好的做法,所以这似乎不是一个好主意.

在Order类中使用静态方法,例如getOrders(args),但我不确定这是静态方法的真正意义.

使用工厂(我从未使用过,遗憾地)处理对象创建(我可能需要一些例子)

在instanciated Order对象中使用方法.这似乎是世界上最糟糕的选择,因为我真的不认为对象应该能够返回自己的集合.

这看起来像是一项非常基本的任务,我猜它是.但我无法找到任何人以“适当”的方式这样做.
我可以添加其他类等(例如DataMappers,Gateways,aso …来处理检索和映射),但我真的不想在我的商务逻辑中与这些类交谈.

提前致谢.

最佳答案 看看
Lazy Load pattern from POEAA

请注意,该图表不建议将逻辑放入从数据库中获取订单到Customer对象.相反,该模式表明:

There are four main varieties of lazy load. Lazy Initialization uses a special marker value (usually null) to indicate a field isn’t loaded. Every access to the field checks the field for the marker value and if unloaded, loads it. Virtual Proxy is an object with the same interface as the real object. The first time one of its methods are called it loads the real the object and then delegates. Value Holder is an object with a getValue method. Clients call getValue to get the real object, the first call triggers the load. A ghost is the real object without any data. The first time you call a method the ghost loads the full data into its fields.

对于其他模式,请考虑Repository并查看Data Source Architectural Patterns.通常,当您有很多对象 – 关系行为问题时,请考虑使用ORM,如Doctrine2.

点赞