Sahid Ferdjaoui Blog - Funraill Foundation Bienvenue, Log in - thème 2007 RC1

Powered by OpenSource Softwares

Outil de déboggage colaborative
reduire

Pattern, Service Locator ou Registry en PHP

le 19 mars 2007 par sahid

Le modÚle de conception Service Locator / Registry mis en situation dans un MVC

Introduction

Le Service Locator, est un pattern permettant la sauvegarde et la restitution d’objets, pour cela, il utilise un tableau par lequel il garde en memoire les objets. Dans une application utilisant le motif MVC, l’utilisation de registre apparait comme une bonne methode sachant que l’application est centrée sur un seul fichier, “index.php”.

Avant d’expliquer comment le mettre en oeuvre, on va d’abord le mettre en situation dans un cas concret.
Notre application est concue sur un modele MVC et tourne autour du fichier index.php.

Aborescence de notre application :

  • /app/controllers
  • /app/models
  • /app/views
  • /index.php

index.php

  1. <?php
  2. // charge le MVC
  3. require_once ("app/MVC.php");
  4. // pattern Service Locator
  5. require_once ("app/ServiceLocator.php");
  6.  
  7. try {
  8.         // Initialise le FC
  9.         $fc = new FrontController ("/app/controllers/");
  10.        
  11.         // Initialisation du modele i18n
  12.         require_once ("/app/models/I18n.php");
  13.         $i18n = new I18n ("fr_FR", "i18n/");
  14.        
  15.         // Sauvegarde du modele en registre
  16.         ServiceLocator::register ("i18n", $i18n); //!\
  17.        
  18.         // Demarre l’appli
  19.         $fc->dispatch (new HttpRequest (), new View ("/app/views/"));
  20. } catch (Exception $e) {
  21.         echo $e->getMessage ();
  22.         die ();
  23. }
  24. ?>

On peut s’apercevoir que dans le fichier index.php on crée l’instance de notre modele I18n. Ensuite par l’intermediaire de ServiceLocator, on le place en registre.

Le controlleur : IndexAction.php

  1. <?php
  2. class IndexAction extends Controller
  3. {
  4.         public function doAction (HttpRequest $request, View $view) {
  5.                 try
  6.                 {
  7.                         // Recupere l’objet i18n enregistre en registre (:
  8.                         $i18n = ServiceLocator::registry ("i18n");      //!\
  9.                        
  10.                         $i18n->setLangue ("en_US");
  11.                         $view->bonjour = $i18n->__(‘bonjour_le_monde’);
  12.                         echo $view->render ("default.tpl.php");
  13.                        
  14.                 } catch (Exception $e) {
  15.                         echo $e->getMessage ();
  16.                         die ();
  17.                 }
  18.         }
  19. }
  20. ?>

Maintenant on récupere notre objet afin de l’utiliser dans notre controlleur IndexAction.php. On remarque que notre application dispose d’une seule occurence I18n pouvant etre utilisée dans tout les controlleurs.

La classe Service Locator

Rien de compliqué dans cette classe, on se sert simplement de methodes et attributs statiques, le tout est de bien faire attention à eviter les doublons, et retourner les bons messages d’erreur en cas d’une mauvaise utilisation de celui-ci.

  1. <?php
  2. class ServiceLocator
  3. {
  4.         static private $_registry = array ();
  5.  
  6.         /**
  7.          * Enregistre un objet dans le registre
  8.          *
  9.          * @param string $key
  10.          * @param objet $obj
  11.          */
  12.         static public function register ($key, $obj)
  13.         {
  14.                 // Verifie les doublons de clefs
  15.                 if (array_key_exists ($key, self::$_registry)) {
  16.                         throw new Exception ("La clef {$key} est deja enregisté.");
  17.                 }
  18.                
  19.                 // Verifie s’il s’agit bien d’un objet
  20.                 if (!is_object ($obj)) {
  21.                         throw new Exception ("Vous pouvez enregister seulement des objets.");
  22.                 }
  23.                
  24.                 // pas de probleme, on enregistre
  25.                 self::$_registry[$key] = $obj;
  26.         }
  27.        
  28.         /**
  29.          * Restaure un objet enregistré
  30.          *
  31.          * @param string $key
  32.          * @return objet
  33.          */
  34.         static public function registry ($key)
  35.         {
  36.                 if (!array_key_exists ($key, self::$_registry)) {
  37.                         throw new Exception ("Aucun objet enregistré sous ce nom");
  38.                 }
  39.                
  40.                 return self::$_registry[$key];
  41.         }
  42. }
  43. ?>

L’utilisation de ce pattern est interessant car il permet d’eviter tout code superflu, et optimise un maximun l’application, dans le sens où on l’utilise à la maniere d’un Singleton une seule instance de nos modeles, et cette instance est disponible partout dans notre application.

Ajouter un commentaire pour Pattern, Service Locator ou Registry en PHP

  • levitra versus cialis
  • ingredient in phentermine
  • lipitor drug
  • generic trileptal
  • januvia 100 mg
  • gabapentin 100 mg
  • new anxiety drugs
  • keppra
  • reglan 10 mg
  • order prednisolone
  • fluticasone propionate
  • rogaine coupons
  • yasmin prescription
  • singulair 5 mg
  • sexual stamina tips
  • alavert drug
  • revatio 20 mg
  • lexapro drugs
  • european pharmacy anxiety
  • attacking anxiety and depression
  • cheap retin a
  • drugs for depression
  • cialis table
  • singulair 10 mg
  • penis enlargement exercises
  • cephalexin sinus
  • phentermine no prescription
  • order nolvadex
  • green tea pill
  • cialis advertisement
  • supplement hoodia
  • cheap viamax
  • valium without prescription
  • fosamax generic
  • cialis name brand cheap
  • ambien dosage
  • viagra and blood pressure
  • xanax rx
  • order viagra without prescription
  • atacand
  • buy prandin
  • cheap yohimbe
  • half life of valium
  • order capoten
  • alprazolam cheap
  • buy cialis by check
  • vitamins for erectile dysfunction
  • klonopin medication
  • drugs used to treat depression
  • online claritin
  • buy cialis online uk
  • benadryl loratadine
  • anxiety meds online
  • asthma in elderly
  • propecia 1mg
  • levitra vardenafil generic
  • cialis online discount
  • order cialis professional
  • clomid treatment
  • medicine xanax
  • methylsulfonylmethane
  • xanax mechanism of action
  • pharmacy online australia
  • cialis vs viagra
  • order lisinopril
  • viagra online best price
  • increase penis size with herbs
  • oxybutynin
  • bayer levitra online pharmacy
  • phentermine consultation
  • free levitra samples
  • acticin cream
  • ventolin inhalador
  • natural viagra substitute
  • glipizide side effects
  • benadryl dosing
  • new treatments for lung diseases
  • viagra jelly
  • types of antidepressants
  • perennial allergic rhinitis
  • mebendazole
  • levitra ad
  • cheap hangover helper
  • interaction zocor
  • cheapest cialis generic
  • cialis cost low
  • clonazepam .5mg
  • kamagra oral jelly
  • ativan no prescription
  • gerd in children
  • prozac social anxiety
  • antidepressant pill high
  • how to cure depression
  • use imitrex
  • cheap robaxin
  • what are the effects of klonopin
  • how to buy viagra online
  • coral calcium
  • canada in levitra
  • cheap viagra pill
  • discount levitra purchase
  • buy levothroid
  • purchase vardenafil
  • online tramadol
  • cialis dosage 20mg
  • viagra soft tab
  • norvasc 10
  • sample ambien
  • lamictal drug
  • herb echinacea
  • effects side ultram
  • endep
  • bayer levitra professional pro
  • addiction ultram
  • giant eagle pharmacy
  • benfotiamine
  • green tea capsule
  • cheap male enhancement
  • order caffeine
  • how much is viagra
  • drug ceftin
  • sumatriptan
  • cialis tablet
  • danazol
  • soma the drug
  • medication for bipolar disorder
  • cozaar medication
  • recreational use of xanax
  • cheap avandia
  • zithromax medication
  • buy lorazepam without prescription
  • reglan side effects
  • drug skelaxin
  • canada pharmacy viagra
  • buy zelnorm
  • phentermine no prescription overnight
  • impotence depression
  • buy ampicillin
  • levitra for sale
  • viagra patent lawsuit levitra
  • cialis vs viagra vs levitra
  • metformin hcl 500mg
  • ways to relieve anxiety
  • order rimonabant
  • natural prednisone
  • generic orlistat
  • nitroglycerin sublingual
  • wellbutrin paxil
  • schizophrenia drugs new zealand
  • lasix furosemide
  • unisom online
  • viagra half price pharmacy
  • manufacturer of revatio
  • clomiphene tablets
  • valium low cost
  • vpxl uk
  • ibuprofen
  • buy probenecid
  • buy etodolac
  • cialis canadian generic
  • stop smoking gum
  • order topamax
  • celebrex pharmacy
  • stop smoking zyban
  • purchase cheap cialis online
  • children aspirin
  • treatment for impotence
  • cialis line order
  • what prednisone
  • buy cialis by the pill
  • buying ultram no prescription
  • venlafaxin
  • buy generic tramadol no prescription
  • allegra side effects
  • prescription nexium
  • order starlix
  • serevent
  • soft tab viagra
  • effects of premarin
  • cheap lovastatin
  • order amantadine
  • viagra and cialis
  • discount levitra online
  • meds for erectile dysfunction
  • sale carisoprodol
  • effects propecia
  • on rx legal diazepam
  • effects of viagra on women
  • buy generic allergy medication
  • ciallis or viagra
  • cheap imitrex
  • order amoxicillin
  • ativan normal doses
  • generic cialis soft
  • purchase phentermine mexico
  • saw palmetto products
  • buy ativan online
  • discount soma online
  • allegra order
  • genric viagra