Skip to content

Adapter

Problématique

Comment faire fonctionner ensemble deux composants logiciels incompatibles?

Solution

// Voici notre adaptateur : il doit reprendre l'ensemble  des méthodes publiques de l'objet PDO
class PdoToMysqli
{
	private $connexion = null ;
 
	public function __construct($dsn, $username = '', $password = '', $driver_options = array())
	{
		preg_match('/host=([^;]+)/', $dsn, $hote) ;
		preg_match('/dbname=([^;]+)/', $dsn, $db) ;
		preg_match('/port=([^;]+)/', $dsn, $port) ;
 
		$this->connexion = new mysqli($hote[1], $username, $password, $db[1], $port[1]) ;
	}
 
	public function query($statment)
	{
		$resultat = $this->connexion->query($statment) ;
		return new PdoStmtToMysqliResult($resultat) ;
	}
}
 
class PdoStmtToMysqliResult
{
	private $result ;
 
	public function __construct($result)
	{
		$this->result = $result ;
	}
 
	public function fetch( $fetch_style = 0, $cursor_orientation = 0, $cursor_offset = 0)
	{
		switch($fetch_style)
		{
			case PDO::FETCH_ASSOC :
				return $this->result->fetch_assoc() ;
				break ;
		}
	}
}

ATTENTION : Normalement, un adapter doit reprendre l’ensemble de l’interface publique de l’objet qu’il « simule »