diff --git a/Strategy/ComparatorInterface.php b/Strategy/ComparatorInterface.php new file mode 100644 index 0000000..468a614 --- /dev/null +++ b/Strategy/ComparatorInterface.php @@ -0,0 +1,17 @@ +elements = $elements; + } + + /** + * @return array + */ + public function sort() + { + $callback = array($this->comparator, 'compare'); + uasort($this->elements, $callback); + + return $this->elements; + } + + /** + * @param ComparatorInterface $comparator + * + * @return void + */ + public function setComparator(ComparatorInterface $comparator) + { + $this->comparator = $comparator; + } +} diff --git a/Strategy/Strategy.php b/Strategy/Strategy.php deleted file mode 100644 index 45187b7..0000000 --- a/Strategy/Strategy.php +++ /dev/null @@ -1,111 +0,0 @@ -_elements = $elements; - } - - /** - * @return array - */ - public function sort() - { - $callback = array($this->_comparator, 'compare'); - uasort($this->_elements, $callback); - - return $this->_elements; - } - - /** - * @param Comparator $comparator - * @return void - */ - public function setComparator(Comparator $comparator) - { - $this->_comparator = $comparator; - } -} - -class IdComparator implements Comparator -{ - public function compare($a, $b) - { - if ($a['id'] == $b['id']) { - return 0; - } else { - return $a['id'] < $b['id'] ? -1 : 1; - } - } -} - -class DateComparator implements Comparator -{ - public function compare($a, $b) - { - $aDate = strtotime($a['date']); - $bDate = strtotime($b['date']); - - if ($aDate == $bDate) { - return 0; - } else { - return $aDate < $bDate ? -1 : 1; - } - } -} - -$elements = array( - array( - 'id' => 2, - 'date' => '2011-01-01', - ), - array( - 'id' => 1, - 'date' => '2011-02-01' - ) -); - -$collection = new ObjectCollection($elements); -$collection->setComparator(new IdComparator()); -$collection->sort(); - -$collection->setComparator(new DateComparator()); -$collection->sort(); \ No newline at end of file diff --git a/Strategy/index.php b/Strategy/index.php new file mode 100644 index 0000000..d59819a --- /dev/null +++ b/Strategy/index.php @@ -0,0 +1,39 @@ + 2, + 'date' => '2011-01-01', + ), + array( + 'id' => 1, + 'date' => '2011-02-01' + ) +); + +$collection = new ObjectCollection($elements); +$collection->setComparator(new IdComparator()); +$collection->sort(); + +$collection->setComparator(new DateComparator()); +$collection->sort();