2

I have several objects of type Item. The items are ordered but their ordering can change, so to make this ordering easy, I don't want to give each item its own order property. I think it might be best to have the List store each Item as it gets created into an array maybe, and the item's order gets decided that way. (first of all, any design issues with this approach?)

My question is how can I still get the order of an Item by contacting the item itself? Ideally I want to do something like this

$item = new Item();
$item->getOrder();

The item has to depend on the List to get its order, so how should it do it?

I'm not fully decided on storing Items in an array in the List. Any other structure that makes things easier is fine. I'm trying to do this in a good OOP way.

Jim Nomy
  • 23
  • 2

1 Answers1

2

If the item has to know the list, add the list as a property of the item, for example parentList.

If you want to ask the List for the order of a particular item, create inside the List a method for that.

function orderOf($item){...}

so now inside your

$item->getOrder() 

simply query your list

$list = $item->parentList();
return $list->orderOf($this);
thomas.g
  • 3,894
  • 3
  • 29
  • 36
  • +1. The use of interfaces might further improve this approach so you can be sure that every List used supportes the `orderOf` method and the Item s can have different types of lists. – Dan Dec 25 '11 at 12:51
  • @Dan I don't understand the `Items can have different types of lists` bit. Did you mean types or "instances"? Could you please explain? – Jim Nomy Dec 25 '11 at 13:12
  • 1
    Types. As long as a class implements the List interface you'll be able to use it in your example. For example you can create the List interface and classes that a implements it: OrderedList, TenElementsMaxList, GroceryList, SuperFastList, etc... – thomas.g Dec 25 '11 at 13:15
  • Indeed, types as luxquarta said. – Dan Dec 25 '11 at 13:17
  • luxquarta and Dan Cool, i get it now. – Jim Nomy Dec 25 '11 at 13:20