views:

307

answers:

3

I have an array of objects, and want the objects to be able to reference their 'neighbors' (the next and previous objects in the array). Is there an existing pattern to do that?

Perhaps the array should be wrapped in an object (since the object can be iterated just as well as the array). That's fine too, I'm just looking for an existing good-practice pattern.

+3  A: 

Described problem looks very similar to usual linked list. You can just add next and prev fields into your object, or in case you don't want to change it, you can create a wrapper object which will contain the original and will have those fields. Or in case the array is global enough to store only your current index inside the array and then it's very simple to get your neighbors.

Artem Barger
That's what I was planning on doing - just didn't know if there was a better pattern (or better for php's oop) than that. Than I'd wrap the array in a class to reassign the references when a member is removed.
Tim Lytle
+1  A: 

I'd consider using the Iterator interface with your wrapper object. #sounds like this would be the "existing good practice" that you're looking for.

Kieran Hall
+1  A: 

Depending on the version of PHP you are running, the SPL provides a SplDoublyLinkedList class that provides all the primary features of a doubly linked list.

jason
Thanks, looks like that could work just fine.
Tim Lytle
Except that it (SplDoublyLinkedList) currently misses methods to insert/remove nodes from somewhere in the middle
Anti Veeranna