Proxy
Problématique
On peut distinguer deux proxy :
- Protection Proxy : Il permet d’implémenter une gestion des droits par dessus une fonctionnalité
Ce desgin pattern intervient dans le principe de la séparation des responsabilités : le composant logiciel ne doit avoir qu’un seul rôle. Ex : la classe de gestion des messages d’un forum ne doit pas gérer les droits d’acces à l’intérieur d’elle même - Remote Proxy : Il permet de retarder au maximum la construction totale d’un objet
Ce désigne pattern intervient dans le cas où un objet est long à construire en entier
Solution
class Produit { private $reference = '' ; private $libelle = '' ; private $categorie = '' ; private $prix = 0.0 ; private $identifiant = null ; public function __construct($reference, $libelle, $categorie, $prix, $identifiant = null) { $this->reference = $reference ; $this->libelle = $libelle ; $this->categorie = $categorie ; $this->prix = $prix ; $this->identifiant = $identifiant ; } public function __call($nom, $parametres) { if(strpos($nom, 'get') !== 0 ) throw new BadMethodCallException() ; $propriete = strtolower(substr($nom, 3)) ; return $this->$propriete ; } } class Catalogue { private $produits = array() ; public function ajouter(Produit $p) { $this->produits[] = $p ; } public function getProduit($index) { return $this->produits[$index] ; } public function getNbProduits() { return count($this->produits) ; } } function databaseConnection() { static $connexion = null ; if(is_null($connexion)) $connexion = new PDO('mysql:host=localhost;dbname=catalogue;port=3306', 'root') ; return $connexion ; } function catalogueFactory() { $connexion = databaseConnection() ; $resultat = $connexion->query('SELECT * FROM produits') ; $catalogue = new Catalogue() ; while($enregistrement = $resultat->fetch(PDO::FETCH_ASSOC)) { $catalogue->ajouter( new Produit( $enregistrement['reference'], $enregistrement['libelle'], $enregistrement['categorie'], $enregistrement['prix'], $enregistrement['id_produit'] ) ) ; } return $catalogue ; } class CatalogueProxy { private $catalogue ; private $nb_produits ; public function getNbProduits() { if(is_null($this->nb_produits)) { $connexion = databaseConnection() ; $resultat = $connexion->query('SELECT COUNT(*) AS nb_produits FROM produits') ; $record = $resultat->fetch(PDO::FETCH_ASSOC) ; $this->nb_produits = $record['nb_produits'] ; } return $this->nb_produits ; } function __call($name, $param) { if(is_null($this->catalogue)) { $this->catalogue = catalogueFactory() ; } return call_user_func_array( array( $this->catalogue, $name) , $param) ; } } $catalogue = new CatalogueProxy() ; var_dump($catalogue) ; echo $catalogue->getNbProduits() ; var_dump($catalogue) ; $catalogue->getProduit(0) ; var_dump($catalogue) ;
Commentaires récents