Design pattern registry

<?php
class Registry {
    private static $_registry = array();
 
    public static function add($name, $value) {
        self::$_registry[$name] = $value;
    }
 
    public static function get($name) {
        if(!self::exists($name))
            throw new Exception(sprintf('<%s> was not registered', $name));
 
        return self::$_registry[$name];
    }
 
    public static function exists($name) {
        if(array_key_exists($name, self::$_registry))
            return true;
        return false;
    }
}
 
Registry::add('logger', new Logger(new Logger_File('./logs/'.date('Y-m-d').'.log')));
$logger = Registry::get('logger');

Design pattern strategy

<?php
interface IFormater {
  public function format($message, $level);
}
 
class File_Xml implements IFormater {
  public function format($message, $level) {
    $date = date('Y-m-d H:i:s');
    $xml = '<message>'.PHP_EOL;
    $xml .= '  <date>'.$date.'</date>'.PHP_EOL;
    $xml .= '  <level>'.$level.'</level>'.PHP_EOL;
    $xml .= '  <desc>'.$message.'</desc>'.PHP_EOL;
    $xml .= '</message>'.PHP_EOL;
    return $xml;
  }
}
 
class File_Csv implements IFormater {
  public function format($message, $level) {
    $plain = date('Y-m-d H:i:s').';'.$level.';'.$message;
    return $plain.PHP_EOL;
  }
}
 
class Logger {
  private $_formater;
  private $_file;
 
  public function __construct(IFormater $formater, $file) {
    $this->_formater = $formater;
    $this->_file = $file;
  }
 
  public function write($message, $level = 'NOTICE') {
    $message = $this->_formater->format($message, $level);
    file_put_contents($this->_file, $message, FILE_APPEND | LOCK_EX);
  }
}
 
$logger = new Logger(new File_Csv(), '/tmp/log.csv');
$logger->write('this is an error test', 'ERROR');
$logger->write('this is a warning test', 'WARNING');
$logger->write('this is a notice test', 'NOTICE');

Design pattern observer

<?php
interface IObserver {
  public function onNew($sender, $arguments);
  public function onChange($sender, $arguments);
}
 
interface IObservable {
  public function addObserver(IObserver $observer);
}
 
class Users implements IObservable {
  private $_observers = array();
 
  public function addObserver(IObserver $observer) {
    $this->_observers[] = $observer;
  }
 
  public function addUser($name) {
    foreach($this->_observers as $observer)
      $observer->onNew($this, $name);
  }
 
  public function updateUser($name) {
    foreach($this->_observers as $observer)
      $observer->onChange($this, $name);
  }
}
 
class UsersLogger implements IObserver {
  public function onNew($sender, $arguments) {
    echo 'New user '.$arguments.'<br />';
  }
 
  public function onChange($sender, $arguments) {
    echo $arguments.' updated<br />';
  }
}
 
class MailUser implements IObserver {
  public function onNew($sender, $arguments) {
    echo 'Sendind account information to '.$arguments.'<br />';
  }
 
  public function onChange($sender, $arguments) {
    echo 'Sendind accound updates to '.$arguments.'<br />';
  }
}
 
$users = new Users();
$users->addObserver(new UsersLogger());
$users->addObserver(new MailUser());
$users->addUser('HiO');
$users->addUser('Hyun');
$users->updateUser('HiO');

Design pattern chain of command

<?php
interface ICommand {
  public function onCommand($name, $arguments);
}
 
class CommandChain {
  private $_commands = array();
 
  public function addCommand($command) {
    $this->_commands[] = $command;
  }
 
  public function runCommand($name, $arguments) {
    foreach($this->_commands as $command) {
      if($command->onCommand($name, $arguments))
	return;
    }
  }
}
 
class Html implements ICommand {
  public function onCommand($name, $arguments) {
    if($name !== 'HTML')
      return false;
    header ("Content-Type: text/html");
    echo '<!DOCTYPE html><html><head></head><body><p>'.$arguments.'</p></body></html>';
    return true;
  }
}
 
class Xml implements ICommand {
  public function onCommand($name, $arguments) {
    if($name !== 'XML') return false;
    header("Content-Type: text/xml");
    echo '<?xml version="1.0" encoding="UTF-8" ?><out>'.$arguments.'</out>';
    return true;
  }
}
 
class Plain implements ICommand {
  public function onCommand($name, $arguments) {
    if($name !== 'PLAIN')
      return false;
    echo $arguments;
    return true;
  }
}
 
$chain = new CommandChain();
$chain->addCommand(new Html());
$chain->addCommand(new Xml());
$chain->addCommand(new Plain());
$chain->runCommand('XML', 'test xml');

Design pattern factory

<?php
interface IConfig {
    public function get();
}
 
class Config {
    const INI = 1;
 
    static public function get($file, $type = self::INI) {
        switch($type) {
            case self::INI:
                $config = new Config_Ini($file);
            break;
            default:
                throw new Exception_Config(sprintf('Unkown config type <%s>', $type));
        }
        return $config->get();
    }
}
 
class Config_Ini implements IConfig {
    private $_file;
 
    public function __construct($file) {
        if(!file_exists($file))
            throw new Exception_Config(sprintf('Ini file: %s not found', $file));
        $this->_file = $file;
    }
 
    public function get() {
        $parsed_ini = parse_ini_file($this->_file, true);
        return $parsed_ini;
    }
}
 
$config = Config::get('application.ini', Config::INI);

Mock object example

<?php
interface IDb {
  public function findOne($id);
}
 
class User{
 
  public function __construct(IDb $db) {
    $this->db = $db;
  }
 
  public function get($id) {
    return $this->db->findOne($id);
  }
}
 
class Db implements IDb {
  public function findOne($id) { // simule un row en db                                                                                                                                                                                       
    return array('username' => 'HiO',
                 'email' => 'hio@hio.fr');
  }
}
 
class Db_Test implements IDb {
  public function findOne($id) {
    return array('username' => 'testUser',
                 'email' => 'test@email.fr');
  }
 
}
 
$user = new User(new Db());
$u1 = $user->get(1);
print_r($u1);
 
$user = new User(new Db_Test());
$u2 = $user->get(564);
print_r($u2);
Array
(
    [username] => HiO
    [email] => hio@hio.fr
)
Array
(
    [username] => testUser
    [email] => test@email.fr
)

PHP iterative constructs

while

$i = 0;
while($i < 10) {
  echo $i.PHP_EOL; // 0 1 ...... 8 9
  $i++;
}
 
$i = 10;
do {
  echo $i.PHP_EOL; // 10 because in a do while loop the code will be executed a least once
  $i++;            // even if the condition never true
} while($i < 10);

for

for($i = 0;$i < 10; $i++) {
  echo $i.PHP_EOL; // 0 1 ...... 8 9
}
 
for($i = 0, $j = 10;$i < 10, $j > 0 ; $i++, $j--) {
  echo $i.' '.$j.', '.PHP_EOL; // 0 10, ... 4 6, ... ,9 1
}

break/continue

$i = 0;
while($i < 10) {
  if($i == 5) {
    break;
  }
  echo $i.PHP_EOL; // 0 1 2 3 4
  $i++;
}
 
$i = 0;
while($i < 10) {
  for($j = 0; $j < 10; $j++) {
    if($j + $i == 15) {
      echo $j.' + '.$i; // 9 + 6
      break 2; // exit from this loop and the next one
    }
  }
  echo $i.PHP_EOL; // 0 1 2 3 4 5
  $i++;
}
 
for($i = 0;$i < 10; $i++) {
  if($i > 3 && $i < 7) {
    continue;
  }
  echo $i.PHP_EOL; // 0 1 2 3 7 8 9
}

PHP conditionals structures

if elseif else

$var1 = true;
$var2 = false;
$var3 = 'php';
 
if($var1) {
  $a = 1;
} elseif(!$var2) {
  $a = 2;
} else {
  $a = 3;
}
echo $a; // 1
 
if($var1) {
  if($var2) {
    $a = 1;
  } else {
    $a = 2;
  }
}
echo $a; // 2
 
if(!$var2) {
  if(!$var1) {
    $a = 1;
  } elseif($var3) { // string (!= 0) to boolean always true
    $a = 2;
  } else {
    $a = 3;
  }
} else {
  $a = 4;
}
echo $a; // 2

ternary operator

$i = 2;
echo 1 == $i ? 'true':'false'; // false
 
$i = 2;
echo 1 != $i ? 'true':'false'; // true
 
$i = 2;
echo 2 == $i ? 'true':'false'; // true

switch

$var = true;
switch ($var) {
case true:
  $a = 1;
  break;
case false:
  $a = 2;
  break;
default:
  $a = 3;
}
echo $a; // 1
 
 
$var = 'php';
switch ($var) {
case true:
  $a = 1;
  break;
case false:
  $a = 2;
  break;
default:
  $a = 3;
}
echo $a; // 1, $var evaluate to true string (!= 0) to boolean always true
 
$var = 'php';
switch ($var) {
case 'perl':
  $a = 1;
  break;
case 'python':
  $a = 2;
  break;
default:
  $a = 3;
}
echo $a; // 3

PHP logical operators

$var1 = true;
$var2 = false;
$var3 = 'php';
 
echo $var1; // true
echo !$var1; // false
echo $var2; // false
echo !$var2; // true
 
if($var1 && $var2)
  $a = 'ok';
else
  $a = 'ko';
 
echo $a; // ko because $var1 and $var2 are not true
 
if($var1 || $var2)
  $a = 'ok';
else
  $a = 'ko';
 
echo $a; // ok because $var1 or $var2 is true
 
$var2 = true;
if($var1 XOR $var2)
  $a = 'ok';
else
  $a = 'ko';
 
echo $a; // ko because $var1 and $var2 are true, but XOR allow only one at true not both
 
echo (boolean)$var3; // true
echo !$var3; // false