The right way to create a list of objects

I always wondered how I should write and which design template to use to create lists of objects.

First of all, consider that I have a Customer class and an Order class. I would like to receive all Orders owned by the User.

I would like $ oCustomer-> getOrders (); to return an array of Order objects.

Basically, I thought:

The OrderManager class, which is singleton and has the ability to extract order data from the storage engine and create Order objects. But I read everywhere that this is bad practice, so this does not seem to be a good idea.

Using static methods in the Order class, such as getOrders (args), but I'm not sure what the real point of static methods are.

Using Factory (which I never used, unfortunately) to handle object creation (maybe I need some examples)

Using a method in an Order object. This seems like the worst option in the world since I really don't think the object should be able to return its own collection.

It looks like a very simple task that I assume. But I could not find someone who would give the โ€œrightโ€ way to do this. I'm fine with adding other classes, etc. (For example, DataMappers, Gateways, aso ... for search processing and matching), but I really don't want to talk to them in my business logic.

Thanks in advance.

+4
source share
2 answers

Check out the Lazy Load pattern from POEAA :

Lazy Load pattern from POEAA

Please note that the diagram does not offer to place the logic for extracting Orders from the database into the Customer object. Instead, the template suggests:

There are four main varieties of lazy exercise. Lazy Initialization uses a special marker value (usually null) to indicate that the field is not loaded. Each access to the field checks the field for the value of the marker and, if it is unloaded, loads it. A virtual proxy is an object with the same interface as a real object. For the first time, one of its methods is called loading a real object, and then delegates. A value holder is an object with the getValue method. Call getValue clients get a real object, the first call causes a load. a ghost is a real object without any data. When the method is first called, the ghost loads the full data into its fields.

For additional templates, review the Repository and see Architectural Data Source Templates . In general, when you have a lot of problems with Object-Relational Behavioral, consider using an ORM like Doctrine2.

+2
source

You can use one class that represents a database connection, one data access object that uses this and one class for the actual object.

http://en.wikipedia.org/wiki/Data_access_object

0
source

Source: https://habr.com/ru/post/1392891/


All Articles