Mysql join

Database

CREATE TABLE IF NOT EXISTS `author` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
 
INSERT INTO `author` (`id`, `name`) VALUES
(1, 'HiO'),
(2, 'Blu'),
(3, 'Pouet');
 
CREATE TABLE IF NOT EXISTS `post` (
  `a_id` INT(10) UNSIGNED DEFAULT NULL,
  `title` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
INSERT INTO `post` (`a_id`, `title`) VALUES
(1, 'My name is HiO :)'),
(NULL, 'I am an anonymous :)'),
(2, 'My name is Blu :D'),
(3, 'My name is Pouet ><''');

INNER JOIN

SELECT * FROM `post` INNER JOIN author ON post.a_id = author.id

Result

$post = array(
  array('a_id'=>'1','title'=>'My name is HiO :)','id'=>'1','name'=>'HiO'),
  array('a_id'=>'2','title'=>'My name is Blu :D','id'=>'2','name'=>'Blu'),
  array('a_id'=>'3','title'=>'My name is Pouet ><\'','id'=>'3','name'=>'Pouet')
);

LEFT JOIN

SELECT * FROM `post` LEFT JOIN author ON post.a_id = author.id

Result

$post = array(
  array('a_id'=>'1','title'=>'My name is HiO :)','id'=>'1','name'=>'HiO'),
  array('a_id'=>NULL,'title'=>'I am an anonymous :)','id'=>NULL,'name'=>NULL),
  array('a_id'=>'2','title'=>'My name is Blu :D','id'=>'2','name'=>'Blu'),
  array('a_id'=>'3','title'=>'My name is Pouet ><\'','id'=>'3','name'=>'Pouet')
);

RIGHT JOIN

SELECT * FROM `author` RIGHT JOIN post ON author.id = post.a_id

Result

$author = array(
  array('id'=>'1','name'=>'HiO','a_id'=>'1','title'=>'My name is HiO :)'),
  array('id'=>NULL,'name'=>NULL,'a_id'=>NULL,'title'=>'I am an anonymous :)'),
  array('id'=>'2','name'=>'Blu','a_id'=>'2','title'=>'My name is Blu :D'),
  array('id'=>'3','name'=>'Pouet','a_id'=>'3','title'=>'My name is Pouet ><\'')
);

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 singleton

<?php
class Logger {
  static $file = null;
 
  private function __construct() {}
 
  public static function get() {
    if(is_null(self::$file))
      self::$file = fopen(date('Y-m-d').'.log', 'a+');
    return self::$file;
  }
}
 
var_dump(Logger::get(), Logger::get());

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);

.vimrc de base

set nocompatible
set bs=2
set background=dark
set wrapmargin=8
syntax on
set ruler
set showcmd
 
set tabstop=4
set shiftwidth=4
set expandtab
 
set fileformats=unix
 
set ignorecase
set incsearch
 
set showmatch

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
)

rewrite rules

redirect HOST != ‘blog.hio.fr’ to blog.hio.fr

RewriteEngine on
RewriteCond %{HTTP_HOST} !^blog\.hio\.fr$ [NC]
RewriteRule ^(.*)$ http://blog.hio.fr/$1? [L,R=301]