start a restructure

This commit is contained in:
Antonio Spinelli
2014-03-21 18:03:44 -03:00
parent b0b0d4a1a4
commit e59d70a0ac
180 changed files with 21 additions and 16 deletions

View File

@@ -0,0 +1,17 @@
<?php
namespace DesignPatterns\Strategy;
/**
* Class ComparatorInterface
*/
interface ComparatorInterface
{
/**
* @param mixed $a
* @param mixed $b
*
* @return bool
*/
public function compare($a, $b);
}

View File

@@ -0,0 +1,24 @@
<?php
namespace DesignPatterns\Strategy;
/**
* Class DateComparator
*/
class DateComparator implements ComparatorInterface
{
/**
* {@inheritdoc}
*/
public function compare($a, $b)
{
$aDate = strtotime($a['date']);
$bDate = strtotime($b['date']);
if ($aDate == $bDate) {
return 0;
} else {
return $aDate < $bDate ? -1 : 1;
}
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace DesignPatterns\Strategy;
/**
* Class IdComparator
*/
class IdComparator implements ComparatorInterface
{
/**
* {@inheritdoc}
*/
public function compare($a, $b)
{
if ($a['id'] == $b['id']) {
return 0;
} else {
return $a['id'] < $b['id'] ? -1 : 1;
}
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace DesignPatterns\Strategy;
/**
* Class ObjectCollection
*/
class ObjectCollection
{
/**
* @var array
*/
private $elements;
/**
* @var ComparatorInterface
*/
private $comparator;
/**
* @param array $elements
*/
public function __construct(array $elements = array())
{
$this->elements = $elements;
}
/**
* @return array
*/
public function sort()
{
if (!$this->comparator){
throw new \LogicException("Comparator is not set");
}
$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;
}
}

View File

@@ -0,0 +1,16 @@
# Strategy
## Terminology:
* Context
* Strategy
* Concrete Strategy
## Purpose
To separate strategies and to enable fast switching between them. Also this pattern is a good alternative to inheritance (instead of having an abstract class that is extended).
## Examples
* sorting a list of objects, one strategy by date, the other by id
* simplify unit testing: e.g. switching between file and in-memory storage

View File

@@ -0,0 +1,21 @@
<?php
namespace DesignPatterns\Strategy;
$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();