The strategy pattern is a software design pattern, whereby an algorithm's behaviour can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.
<?php
interface StrategyInterface
{
public function find($strategy);
}
class Users
{
private $users = array();
public function add($users)
{
$this->users = $users;
}
public function filter($filter)
{
foreach ($this->users as $user)
{
if ($filter->find($user))
{
echo 'User filtered: ' . $user . PHP_EOL;
}
}
}
}
class RandomStrategy implements StrategyInterface
{
public function find($string)
{
return rand(0,1);
}
}
class StringStragey implements StrategyInterface
{
public $string = '';
public function __construct($string)
{
$this->string = $string;
}
public function find($string)
{
return $this->string == $string;
}
}
$users = new Users();
$users->add(array('Anton', 'John'));
$users->filter(new RandomStrategy());
$users->filter(new StringStragey('Anton'));
?>