0

I am trying to plan out php class structure for an order processing project. I've used classes before but I'm still not an expert on OOP yet. I've been searching for hours and can't seem to find the answer to this particular scenario, despite it being very common.

One of the main objects will be an Order. As such, that class will have methods to handle getting and setting of all the properties of the Order instance. (It will also have properties containing other objects such as arrays of OrderItems and Fulfillments)

My question is what happens when I need a filtered set of orders from the DB? Making a method in Order that returns an array of.. itself?... definitely isn't right. Is making an Orders class that has methods to handle a single Order as well as an array of Order objects the recommended way to handle this? Or is there another design pattern that is better suited?

A couple of other options would be to return a raw array and let the calling function handle it. Or create an OrderModel that just has a bunch of public properties of an order and the Order class can return that object or an array of OrderModel.

  • 1
    Making a method in Order that returns an array of.. itself? -- It's more likely that you will have an array or collection of orders and will use a filtering operation on that array or collection. See: php.net/manual/en/ds-set.filter.php – Robert Harvey Apr 26 at 15:02
0

I ended up creating a helper class that manages the objects and implements the built in Iterator interface. https://php.net/manual/en/class.iterator.php

class Order {
   // handle single order
}

class OrderList implements Iterator {
   // handle creating an array of Order objects
   // Implement required methods for the Iterator interface
}

// instantiate 
$orderList = new OrderList($filter);
foreach($orderList as $order) {
   // do something with each order
}
0

The need to get a filtered list of orders from the database is a separate concern from the logic of an order itself. It needs to be a separate class from Order. You need a data access object. This new class, say OrderDataAccess can have a method that fetches Order objects from the database and filters them either in-memory on the server or by using WHERE clauses in a SQL query. Same goes for sorting Order objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.