SlideShare une entreprise Scribd logo
1  sur  57
Tirer parti des décorateurs Zend_Form  Mickaël Perraud Contributeur  Zend Framework Responsable documentation française
Qu'est-ce qu'un décorateur ?
Dans Zend_Form … ,[object Object]
Patron  de  conception  Décorateur “ En  programmation  orientée objet, le patron de conception décorateur est un motif qui permet l'ajout dynamique de fonctionnalités à un objet existant.” – Wikipedia, “Décorateur_(patron_de_conception)”
 
Deux techniques principales ,[object Object]
interface Window { public   function   isOpen(); public   function   open(); public   function close (); }
class  StandardWindow implements Window { protected   $_open   =   false; public   function   isOpen() { return   $this ->_open; } public   function   open() { if   (! $this ->_open) {   $this ->_open   =   true;  } } public   function close () { if   ( $this ->_open) {   $this ->_open   =   false; } } }
class  LockedWindow implements Window { protected   $_window ; public   function   __construct(Window   $window ){ $this ->_window   =   $window ; $this ->_window-> close (); } public   function   isOpen() {   return   false; } public   function   open() { throw new Exception( 'Cannot open locked windows' );  } public   function close () {   $this ->_window-> close ();  } }
class  LockedWindow { protected  $_window ; public   function   __construct(Window   $window ) { $this ->_window   =   $window ; $this ->_window-> close (); } public  function  isOpen() {  return  false; } public   function   __call( $method ,   $args ) { if   (! method_exists ( $this ->_window,   $method ))   { throw new   Exception( 'Invalid method' ); } return   $this ->_window-> $method (); } }
Patron  de  conception Stratégie “ Un patron de conception particulier, dans lequel les algorithmes peuvent être sélectionnés lors de l'exécution.” –  Wikipedia, “Strategy_pattern”
 
class  Window { public   $strategy ; public   function   open() { $this -> $strategy ->open(); } } interface OpenStrategy { public   function   open(); }
class  RaiseStrategy implements OpenStrategy { public   function   open() { } } class   LeverStrategy implements OpenStrategy { public   function   open() { } }
Créer votre premier décorateur
L'interface ,[object Object]
setElement($element);
getElement();
setOptions(array $options);
setConfig(Zend_Config $config);
setOption($key, $value);
getOption($key);
getOptions();
removeOption($key);
clearOptions();
render($content);
L'interface ,[object Object]
Un décorateur simple pour un champ texte ,[object Object]
Va rendre le champ texte
Va récupérer les méta-données à partir de l'élément et les utiliser pour définir l'affichage généré
class   My_Decorator_SimpleInput extends   Zend_Form_Decorator_Abstract { protected   $_format   =   '<label for=&quot;%s&quot;>%s</label>' .   '<input id=&quot;%s&quot; name=&quot;%s&quot; type=&quot;text&quot; value=&quot;%s&quot;/>' ; public   function   render( $content ) { $element   =   $this ->getElement(); $name   =   htmlentities ( $element ->getFullyQualifiedName()); $label   =   htmlentities ( $element ->getLabel()); $id   =   htmlentities ( $element ->getId()); $value   =   htmlentities ( $element ->getValue()); $markup   =   sprintf ( $this ->_format,   $name ,   $label ,   $id ,   $name ,   $value ); return   $markup ; } }
$decorator  = new My_Decorator_SimpleInput(); $element   =   new   Zend_Form_Element( 'foo' ,   array ( 'label'   =>   'Foo' , 'belongsTo'   =>   'bar' , 'value'   =>   'test' , 'decorators'   =>   array ( $decorator ), )); $element  = new Zend_Form_Element( 'foo' ,  array ( 'label'   =>   'Foo' , 'belongsTo'   =>   'bar' , 'value'   =>   'test' , 'prefixPath'   =>   array ( 'decorator'   =>   array ( 'My_Decorator'   =>   'path/to/decorators/' , )), 'decorators'   =>   array ( 'SimpleInput' ), ));
<label   for = &quot;bar[foo]&quot; > Foo </label> <input   id = &quot;bar-foo&quot;   name = &quot;bar[foo]&quot;   type = &quot;text&quot;   value = &quot;test&quot; />
Où en sommes-nous ? ,[object Object]
Échappement automatique
Sélection des attributs que vous souhaitez propager et afficher au moment de l'exécution
Superposer les décorateurs
L'argument $content ,[object Object]
Des décorateurs individuels peuvent être spécialisés dans la création d'affichages liés à certaines métadonnées de l'élément
L'affichage final est le produit de tous les décorateurs
Décorateurs par défaut ,[object Object]
Description  – effectue le rendu de la description de l'élément, si besoin
Errors  – effectue le rendu des erreurs de validation, si besoin
HtmlTag  – enveloppe tout le contenu généré dans une balise
Label  – utilise une aide de vue pour effectuer le rendu du libellé de l'élément ; l'ajoute devant le contenu agrégé
 
 
 
 
 
Comment superposer les décorateurs ? ,[object Object]
Choississez de : ,[object Object]
Ajouter avant le contenu fourni (PREPEND)
Remplacer le contenu fourni (REPLACE) ,[object Object]
class  My_Decorator_SimpleInput    extends  Zend_Form_Decorator_Abstract { protected   $_format   =   '<input id=&quot;%s&quot; name=&quot;%s&quot; type=&quot;text&quot; value=&quot;%s&quot;/>' ; public   function   render( $content ) { $element   =   $this ->getElement(); $name   =   htmlentities ( $element ->getFullyQualifiedName()); $id   =   htmlentities ( $element ->getId()); $value   =   htmlentities ( $element ->getValue()); $markup   =   sprintf ( $this ->_format,     $id ,   $name ,   $value ); // On gère le placement ici... return   $markup ; } }
class  My_Decorator_SimpleLabel  extends  Zend_Form_Decorator_Abstract { protected   $_format   =   '<label for=&quot;%s&quot;>%s</label>' ; public   function   render( $content ) { $element   =   $this ->getElement(); $id   =   htmlentities ( $element ->getId()); $label   =   htmlentities ( $element ->getLabel()); $markup   =   sprint( $this ->_format,   $id ,   $label ); // On gère le placement ici... return   $markup ; } }
$placement  =  $this ->getPlacement(); $separator   =   $this ->getSeparator(); switch   ( $placement ) { case self::PREPEND: return   $markup  .  $separator  .  $content ; case self::APPEND: default: return   $content   .   $separator   .   $markup ; } switch   ( $placement ) { case self::APPEND: return   $content  .  $separator  .  $markup ; case self::PREPEND: default: return   $markup  .  $separator  .  $content ; }

Contenu connexe

Tendances

Formulaires Symfony2 - Cas pratiques et explications
Formulaires Symfony2 - Cas pratiques et explicationsFormulaires Symfony2 - Cas pratiques et explications
Formulaires Symfony2 - Cas pratiques et explicationsAlexandre Salomé
 
Formation PHP
Formation PHPFormation PHP
Formation PHPkemenaran
 
Meet up symfony 11 octobre 2016 - Les formulaire
Meet up symfony 11 octobre 2016 - Les formulaireMeet up symfony 11 octobre 2016 - Les formulaire
Meet up symfony 11 octobre 2016 - Les formulaireJulien Vinber
 
Php 2 - Approfondissement MySQL, PDO et MVC
Php 2 - Approfondissement MySQL, PDO et MVCPhp 2 - Approfondissement MySQL, PDO et MVC
Php 2 - Approfondissement MySQL, PDO et MVCPierre Faure
 
Intégration web MMI
Intégration web MMIIntégration web MMI
Intégration web MMIPierre VERT
 
PHP 1 - Apprendre les bases
PHP 1 - Apprendre les basesPHP 1 - Apprendre les bases
PHP 1 - Apprendre les basesPierre Faure
 
PHP #3 : tableaux & formulaires
PHP #3 : tableaux & formulairesPHP #3 : tableaux & formulaires
PHP #3 : tableaux & formulairesJean Michel
 
php2 : formulaire-session-PDO
php2 : formulaire-session-PDOphp2 : formulaire-session-PDO
php2 : formulaire-session-PDOAbdoulaye Dieng
 
Tester les applications Zend Framework
Tester les applications Zend FrameworkTester les applications Zend Framework
Tester les applications Zend FrameworkMickael Perraud
 
Php mysql cours
Php mysql coursPhp mysql cours
Php mysql courszan
 
Programa Educativo 2011 do Museu das Terras de Basto
Programa Educativo 2011 do Museu das Terras de BastoPrograma Educativo 2011 do Museu das Terras de Basto
Programa Educativo 2011 do Museu das Terras de BastoMuseu das Terras de Basto
 
PHP 7 et Symfony 3
PHP 7 et Symfony 3PHP 7 et Symfony 3
PHP 7 et Symfony 3Eddy RICHARD
 

Tendances (20)

Formulaires Symfony2 - Cas pratiques et explications
Formulaires Symfony2 - Cas pratiques et explicationsFormulaires Symfony2 - Cas pratiques et explications
Formulaires Symfony2 - Cas pratiques et explications
 
Formation PHP
Formation PHPFormation PHP
Formation PHP
 
Structure de données en PHP
Structure de données en PHPStructure de données en PHP
Structure de données en PHP
 
Meet up symfony 11 octobre 2016 - Les formulaire
Meet up symfony 11 octobre 2016 - Les formulaireMeet up symfony 11 octobre 2016 - Les formulaire
Meet up symfony 11 octobre 2016 - Les formulaire
 
Php 2 - Approfondissement MySQL, PDO et MVC
Php 2 - Approfondissement MySQL, PDO et MVCPhp 2 - Approfondissement MySQL, PDO et MVC
Php 2 - Approfondissement MySQL, PDO et MVC
 
Le Tracking sur Internet
Le Tracking sur InternetLe Tracking sur Internet
Le Tracking sur Internet
 
Intégration web MMI
Intégration web MMIIntégration web MMI
Intégration web MMI
 
PHP 1 - Apprendre les bases
PHP 1 - Apprendre les basesPHP 1 - Apprendre les bases
PHP 1 - Apprendre les bases
 
Les structures de données PHP5
Les structures de données PHP5Les structures de données PHP5
Les structures de données PHP5
 
PHP #3 : tableaux & formulaires
PHP #3 : tableaux & formulairesPHP #3 : tableaux & formulaires
PHP #3 : tableaux & formulaires
 
SQL et MySQL
SQL et MySQLSQL et MySQL
SQL et MySQL
 
php2 : formulaire-session-PDO
php2 : formulaire-session-PDOphp2 : formulaire-session-PDO
php2 : formulaire-session-PDO
 
Memento Boucles SPIP
Memento Boucles SPIPMemento Boucles SPIP
Memento Boucles SPIP
 
Tester les applications Zend Framework
Tester les applications Zend FrameworkTester les applications Zend Framework
Tester les applications Zend Framework
 
La première partie de la présentation PHP
La première partie de la présentation PHPLa première partie de la présentation PHP
La première partie de la présentation PHP
 
Php mysql cours
Php mysql coursPhp mysql cours
Php mysql cours
 
Programa Educativo 2011 do Museu das Terras de Basto
Programa Educativo 2011 do Museu das Terras de BastoPrograma Educativo 2011 do Museu das Terras de Basto
Programa Educativo 2011 do Museu das Terras de Basto
 
PHP 7 et Symfony 3
PHP 7 et Symfony 3PHP 7 et Symfony 3
PHP 7 et Symfony 3
 
C libro escenarioii
C libro escenarioiiC libro escenarioii
C libro escenarioii
 
Regex php
Regex phpRegex php
Regex php
 

Similaire à Tirer parti des décorateurs de Zend_Form

Patterns and OOP in PHP
Patterns and OOP in PHPPatterns and OOP in PHP
Patterns and OOP in PHPjulien pauli
 
PHP - get started
PHP - get startedPHP - get started
PHP - get startedmazenovi
 
ZendFramework2 - Présentation
ZendFramework2 - PrésentationZendFramework2 - Présentation
ZendFramework2 - Présentationjulien pauli
 
Introduction à Sinatra
Introduction à SinatraIntroduction à Sinatra
Introduction à SinatraRémi Prévost
 
Domi code-igniter-4 i18-n
Domi code-igniter-4 i18-nDomi code-igniter-4 i18-n
Domi code-igniter-4 i18-nAFPA
 
Coat::Persistent at FPW2009
Coat::Persistent at FPW2009Coat::Persistent at FPW2009
Coat::Persistent at FPW2009Alexis Sukrieh
 
Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !Engineor
 
Présentation jQuery pour débutant
Présentation jQuery pour débutantPrésentation jQuery pour débutant
Présentation jQuery pour débutantStanislas Chollet
 
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINE
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINEIntroduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINE
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINEMarouan OMEZZINE
 
PHP 5.3, PHP Next
PHP 5.3, PHP NextPHP 5.3, PHP Next
PHP 5.3, PHP NextSQLI
 
Analyse statique et applications
Analyse statique et applicationsAnalyse statique et applications
Analyse statique et applicationsDamien Seguy
 
Jump Camp - HTML5
Jump Camp - HTML5Jump Camp - HTML5
Jump Camp - HTML5chaudavid
 
Migration PHP4-PHP5
Migration PHP4-PHP5Migration PHP4-PHP5
Migration PHP4-PHP5julien pauli
 
Atelier WordPress: Création d&rsquo;extension WordPress
Atelier WordPress: Création d&rsquo;extension WordPressAtelier WordPress: Création d&rsquo;extension WordPress
Atelier WordPress: Création d&rsquo;extension WordPressIZZA Samir
 

Similaire à Tirer parti des décorateurs de Zend_Form (20)

Patterns and OOP in PHP
Patterns and OOP in PHPPatterns and OOP in PHP
Patterns and OOP in PHP
 
PHP - get started
PHP - get startedPHP - get started
PHP - get started
 
Spring 3.0
Spring 3.0Spring 3.0
Spring 3.0
 
PHP &amp; MySQL
PHP &amp; MySQLPHP &amp; MySQL
PHP &amp; MySQL
 
ZendFramework2 - Présentation
ZendFramework2 - PrésentationZendFramework2 - Présentation
ZendFramework2 - Présentation
 
Apprenez le jQuery
Apprenez le jQueryApprenez le jQuery
Apprenez le jQuery
 
Introduction à Sinatra
Introduction à SinatraIntroduction à Sinatra
Introduction à Sinatra
 
Domi code-igniter-4 i18-n
Domi code-igniter-4 i18-nDomi code-igniter-4 i18-n
Domi code-igniter-4 i18-n
 
Coat::Persistent at FPW2009
Coat::Persistent at FPW2009Coat::Persistent at FPW2009
Coat::Persistent at FPW2009
 
Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !
 
Présentation jQuery pour débutant
Présentation jQuery pour débutantPrésentation jQuery pour débutant
Présentation jQuery pour débutant
 
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINE
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINEIntroduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINE
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINE
 
Introduction à PHP
Introduction à PHPIntroduction à PHP
Introduction à PHP
 
Ruby Pour RoR
Ruby Pour RoRRuby Pour RoR
Ruby Pour RoR
 
PHP 5.3, PHP Next
PHP 5.3, PHP NextPHP 5.3, PHP Next
PHP 5.3, PHP Next
 
Analyse statique et applications
Analyse statique et applicationsAnalyse statique et applications
Analyse statique et applications
 
Introduction a jQuery
Introduction a jQueryIntroduction a jQuery
Introduction a jQuery
 
Jump Camp - HTML5
Jump Camp - HTML5Jump Camp - HTML5
Jump Camp - HTML5
 
Migration PHP4-PHP5
Migration PHP4-PHP5Migration PHP4-PHP5
Migration PHP4-PHP5
 
Atelier WordPress: Création d&rsquo;extension WordPress
Atelier WordPress: Création d&rsquo;extension WordPressAtelier WordPress: Création d&rsquo;extension WordPress
Atelier WordPress: Création d&rsquo;extension WordPress
 

Plus de Mickael Perraud

Présentation de DBAL en PHP (Nantes)
Présentation de DBAL en PHP (Nantes)Présentation de DBAL en PHP (Nantes)
Présentation de DBAL en PHP (Nantes)Mickael Perraud
 
Présentation de DBAL en PHP
Présentation de DBAL en PHPPrésentation de DBAL en PHP
Présentation de DBAL en PHPMickael Perraud
 
Découvrez le noyau d'internationalisation du Zend Framework
Découvrez le noyau d'internationalisation du Zend FrameworkDécouvrez le noyau d'internationalisation du Zend Framework
Découvrez le noyau d'internationalisation du Zend FrameworkMickael Perraud
 
Introduction à Zend Framework 2
Introduction à Zend Framework 2Introduction à Zend Framework 2
Introduction à Zend Framework 2Mickael Perraud
 
Développement sécurisé d'applications avec Zend Framework
Développement sécurisé d'applications avec Zend FrameworkDéveloppement sécurisé d'applications avec Zend Framework
Développement sécurisé d'applications avec Zend FrameworkMickael Perraud
 

Plus de Mickael Perraud (6)

Présentation de DBAL en PHP (Nantes)
Présentation de DBAL en PHP (Nantes)Présentation de DBAL en PHP (Nantes)
Présentation de DBAL en PHP (Nantes)
 
Présentation de DBAL en PHP
Présentation de DBAL en PHPPrésentation de DBAL en PHP
Présentation de DBAL en PHP
 
Découvrez le noyau d'internationalisation du Zend Framework
Découvrez le noyau d'internationalisation du Zend FrameworkDécouvrez le noyau d'internationalisation du Zend Framework
Découvrez le noyau d'internationalisation du Zend Framework
 
Introduction à Zend Framework 2
Introduction à Zend Framework 2Introduction à Zend Framework 2
Introduction à Zend Framework 2
 
Zf2 ce-qui-va-changer
Zf2 ce-qui-va-changerZf2 ce-qui-va-changer
Zf2 ce-qui-va-changer
 
Développement sécurisé d'applications avec Zend Framework
Développement sécurisé d'applications avec Zend FrameworkDéveloppement sécurisé d'applications avec Zend Framework
Développement sécurisé d'applications avec Zend Framework
 

Tirer parti des décorateurs de Zend_Form

  • 1. Tirer parti des décorateurs Zend_Form Mickaël Perraud Contributeur Zend Framework Responsable documentation française
  • 3.
  • 4. Patron de conception Décorateur “ En programmation orientée objet, le patron de conception décorateur est un motif qui permet l'ajout dynamique de fonctionnalités à un objet existant.” – Wikipedia, “Décorateur_(patron_de_conception)”
  • 5.  
  • 6.
  • 7. interface Window { public function isOpen(); public function open(); public function close (); }
  • 8. class StandardWindow implements Window { protected $_open = false; public function isOpen() { return $this ->_open; } public function open() { if (! $this ->_open) { $this ->_open = true; } } public function close () { if ( $this ->_open) { $this ->_open = false; } } }
  • 9. class LockedWindow implements Window { protected $_window ; public function __construct(Window $window ){ $this ->_window = $window ; $this ->_window-> close (); } public function isOpen() { return false; } public function open() { throw new Exception( 'Cannot open locked windows' ); } public function close () { $this ->_window-> close (); } }
  • 10. class LockedWindow { protected $_window ; public function __construct(Window $window ) { $this ->_window = $window ; $this ->_window-> close (); } public function isOpen() { return false; } public function __call( $method , $args ) { if (! method_exists ( $this ->_window, $method )) { throw new Exception( 'Invalid method' ); } return $this ->_window-> $method (); } }
  • 11. Patron de conception Stratégie “ Un patron de conception particulier, dans lequel les algorithmes peuvent être sélectionnés lors de l'exécution.” – Wikipedia, “Strategy_pattern”
  • 12.  
  • 13. class Window { public $strategy ; public function open() { $this -> $strategy ->open(); } } interface OpenStrategy { public function open(); }
  • 14. class RaiseStrategy implements OpenStrategy { public function open() { } } class LeverStrategy implements OpenStrategy { public function open() { } }
  • 15. Créer votre premier décorateur
  • 16.
  • 27.
  • 28.
  • 29. Va rendre le champ texte
  • 30. Va récupérer les méta-données à partir de l'élément et les utiliser pour définir l'affichage généré
  • 31. class My_Decorator_SimpleInput extends Zend_Form_Decorator_Abstract { protected $_format = '<label for=&quot;%s&quot;>%s</label>' . '<input id=&quot;%s&quot; name=&quot;%s&quot; type=&quot;text&quot; value=&quot;%s&quot;/>' ; public function render( $content ) { $element = $this ->getElement(); $name = htmlentities ( $element ->getFullyQualifiedName()); $label = htmlentities ( $element ->getLabel()); $id = htmlentities ( $element ->getId()); $value = htmlentities ( $element ->getValue()); $markup = sprintf ( $this ->_format, $name , $label , $id , $name , $value ); return $markup ; } }
  • 32. $decorator = new My_Decorator_SimpleInput(); $element = new Zend_Form_Element( 'foo' , array ( 'label' => 'Foo' , 'belongsTo' => 'bar' , 'value' => 'test' , 'decorators' => array ( $decorator ), )); $element = new Zend_Form_Element( 'foo' , array ( 'label' => 'Foo' , 'belongsTo' => 'bar' , 'value' => 'test' , 'prefixPath' => array ( 'decorator' => array ( 'My_Decorator' => 'path/to/decorators/' , )), 'decorators' => array ( 'SimpleInput' ), ));
  • 33. <label for = &quot;bar[foo]&quot; > Foo </label> <input id = &quot;bar-foo&quot; name = &quot;bar[foo]&quot; type = &quot;text&quot; value = &quot;test&quot; />
  • 34.
  • 36. Sélection des attributs que vous souhaitez propager et afficher au moment de l'exécution
  • 38.
  • 39. Des décorateurs individuels peuvent être spécialisés dans la création d'affichages liés à certaines métadonnées de l'élément
  • 40. L'affichage final est le produit de tous les décorateurs
  • 41.
  • 42. Description – effectue le rendu de la description de l'élément, si besoin
  • 43. Errors – effectue le rendu des erreurs de validation, si besoin
  • 44. HtmlTag – enveloppe tout le contenu généré dans une balise
  • 45. Label – utilise une aide de vue pour effectuer le rendu du libellé de l'élément ; l'ajoute devant le contenu agrégé
  • 46.  
  • 47.  
  • 48.  
  • 49.  
  • 50.  
  • 51.
  • 52.
  • 53. Ajouter avant le contenu fourni (PREPEND)
  • 54.
  • 55. class My_Decorator_SimpleInput extends Zend_Form_Decorator_Abstract { protected $_format = '<input id=&quot;%s&quot; name=&quot;%s&quot; type=&quot;text&quot; value=&quot;%s&quot;/>' ; public function render( $content ) { $element = $this ->getElement(); $name = htmlentities ( $element ->getFullyQualifiedName()); $id = htmlentities ( $element ->getId()); $value = htmlentities ( $element ->getValue()); $markup = sprintf ( $this ->_format, $id , $name , $value ); // On gère le placement ici... return $markup ; } }
  • 56. class My_Decorator_SimpleLabel extends Zend_Form_Decorator_Abstract { protected $_format = '<label for=&quot;%s&quot;>%s</label>' ; public function render( $content ) { $element = $this ->getElement(); $id = htmlentities ( $element ->getId()); $label = htmlentities ( $element ->getLabel()); $markup = sprint( $this ->_format, $id , $label ); // On gère le placement ici... return $markup ; } }
  • 57. $placement = $this ->getPlacement(); $separator = $this ->getSeparator(); switch ( $placement ) { case self::PREPEND: return $markup . $separator . $content ; case self::APPEND: default: return $content . $separator . $markup ; } switch ( $placement ) { case self::APPEND: return $content . $separator . $markup ; case self::PREPEND: default: return $markup . $separator . $content ; }
  • 58. $element = new Zend_Form_Element( 'foo' , array ( 'label' => 'Foo' , 'belongsTo' => 'bar' , 'value' => 'test' , 'prefixPath' => array ( 'decorator' => array ( 'My_Decorator' => 'path/to/decorators/' , )), 'decorators' => array ( 'SimpleInput' , 'SimpleLabel' , ), ));
  • 59. $element = new Zend_Form_Element( 'foo' , array ( 'label' => 'Foo' , 'belongsTo' => 'bar' , 'value' => 'test' , 'prefixPath' => array ( 'decorator' => array ( 'My_Decorator' => 'path/to/decorators/' , )), 'decorators' => array ( 'SimpleInput' array ( 'SimpleLabel' , array ( 'placement' => 'append' )), ), ));
  • 60. Rendre les décorateurs individuellement
  • 61.
  • 62. Vos designers peuvent vouloir avoir plus de visibilité sur ce qui est rendu
  • 63. Comment ? $decorator = $element ->getDecorator( 'SimpleInput' ); echo $decorator ->render( '' ); Facile : echo $element ->getDecorator( 'SimpleInput' ) ->render( '' ); Plus facile : echo $element ->renderSimpleInput(); Encore plus facile :
  • 64. <div class = &quot;element&quot; > <?php echo $form ->title->renderLabel() . $form ->title->renderViewHelper(); if ( $form ->title->hasErrors()) { echo '<p class=&quot;error&quot;>There were errors validating</p>' ; } ?> </div>
  • 65. <div class = &quot;element&quot; > <?php echo $form ->dateOfBirth->renderLabel() ?> <?php echo $this ->formText( 'dateOfBirth[day]' , '' , array ( 'size' => 2, 'maxlength' => 2)) ?> / <?php echo $this ->formText( 'dateOfBirth[month]' , '' , array ( 'size' => 2, 'maxlength' => 2)) ?> / <?php echo $this ->formText( 'dateOfBirth[year]' , '' , array ( 'size' => 4, 'maxlength' => 4)) ?> </div>
  • 67.
  • 68. Pour une question de confort, on demande à l'utilisateur de renseigner indépendamment le jour, le mois et l'année
  • 69. … mais typiquement ces décorateurs représentent un seul élément de formulaire
  • 70.
  • 71. Accepte les valeurs sous la forme de tableau avec des clés jour/mois/année
  • 72. Accepte les valeurs sous forme de chaîne
  • 73. Possède des accesseurs pour chaque segment de la date (jours, mois et année)
  • 74. class My_Form_Element_Date extends Zend_Form_Element_Xhtml { public function setValue( $value ) { if ( is_int ( $value )) { $this ->_value = new DateTime( date ( 'Y-m-d' , $value )); } elseif ( is_string ( $value )) { $this ->_value = new DateTime( $value ); } elseif ( is_array ( $value )) { $this ->_value = new DateTime(); $this ->_value->setDate( $value [ 'year' ], $value [ 'month' ], $value [ 'day' ] ); } else { throw new Exception( 'Invalid date value provided' ); } return $this ; } public function getDay() { } public function getMonth() { } public function getYear() { } }
  • 75.
  • 76. S'assure de la présence d'une vue
  • 77. Récupère les méta-données à partir de l'élément
  • 78. Fournit les méta-données aux aides de vues existantes pour créer le balisage
  • 79. class My_Form_Decorator_Date extends Zend_Form_Decorator_Abstract { public function render( $content ) { $element = $this ->getElement(); if (! $element instanceof My_Form_Element_Date) { return $content ; } $view = $element ->getView(); if (! $view instanceof Zend_View_Interface) { return $content ; } $day = $element ->getDay(); $month = $element ->getMonth(); $year = $element ->getYear(); $name = $element ->getFullyQualifiedName(); // ... } }
  • 80. class My_Form_Decorator_Date extends Zend_Form_Decorator_Abstract { public function render( $content ) { // ... $params = array ( 'size' => 2, 'maxlength' => 2); $yearParams = array ( 'size' => 4, 'maxlength' => 4); $markup = $view ->formText( $name . '[day]' , $day , $params ) . ' / ' . $view ->formText( $name . '[month]' , $month , $params ) . ' / ' . $view ->formText( $name . '[year]' , $year , $yearParams ); // Placement et valeur de retour ... } }
  • 81.
  • 83. class My_Form_Element_Date extends Zend_Form_Element_Xhtml { // ... public function __construct( $spec , $options = null ) { $this ->addPrefixPath( 'My_Form_Decorator' , 'My/Form/Decorator' , 'decorator' ); parent::__construct( $spec , $options ); } // ... }
  • 84. class My_Form_Element_Date extends Zend_Form_Element_Xhtml { // ... public function loadDefaultDecorators() { if ( $this ->loadDefaultDecoratorsIsDisabled()) { return ; } if (empty( $decorators = $this ->getDecorators() )) { $this ->addDecorator( 'Date' ) // ... ; } } // ... }
  • 85. Maintenant on l'utilise ! $d = new My_Form_Element_Date( 'dateOfBirth' ); $d ->setLabel( 'Date of Birth: ' ) ->setView(new Zend_View()); // Ceux-ci sont équivalents : $d ->setValue( '20 April 2009' ); $d ->setValue( array ( 'year' => '2009' , 'month' => '04' , 'day' => '20' ));
  • 86. <dt id = &quot;dateOfBirth-label&quot; ><label for = &quot;dateOfBirth&quot; class = &quot;optional&quot; > Date of Birth: </label></dt> <dd id = &quot;dateOfBirth-element&quot; > <input type = &quot;text&quot; name = &quot;dateOfBirth[day]&quot; id = &quot;dateOfBirth-day&quot; value = &quot;20&quot; size = &quot;2&quot; maxlength = &quot;2&quot; > / <input type = &quot;text&quot; name = &quot;dateOfBirth[month]&quot; id = &quot;dateOfBirth-month&quot; value = &quot;4&quot; size = &quot;2&quot; maxlength = &quot;2&quot; > / <input type = &quot;text&quot; name = &quot;dateOfBirth[year]&quot; id = &quot;dateOfBirth-year&quot; value = &quot;2009&quot; size = &quot;4&quot; maxlength = &quot;4&quot; > </dd>
  • 88.
  • 89. Comment créer vos propres décorateurs
  • 90. Comment superposer les décorateurs
  • 92. Comment créer des éléments constitués d'entrées composées
  • 93.
  • 94. Créer un visuel personnalisé en utilisant Zend_Form_Decorator : http://framework.zend.com/manual/fr/zend.form.decorators.html
  • 95.

Notes de l'éditeur

  1. An interface
  2. Concrete implementation of the interface
  3. Traditional locked window; implements same interface as decorated object
  4. Duck-typed locked window
  5. UML diagram of strategy pattern. Concrete object allows attaching objects that implement a particular strategy, or interface; it then calls a defined method on the attached object
  6. Calling object and interface for strategy
  7. Implementations of the strategy
  8. Generate simple markup with label and form input
  9. Two ways to use the decorator: (1) attaching the instance (2) setting the plugin path and specifying it by short name
  10. The markup generated
  11. How layering works: * First decorator is passed empty content * First decorator replaces content by rendering a view helper and passing the rendered markup to the next decorator
  12. How layering works: * Second decorator pulls the element description, if any, and renders it using formNote() view helper; then appends it and passes it to the third decorator
  13. How layering works: * Third decorator pulls any validation errors, and, if found, passes them to the formErrors() view helper; this is also appended to the content passed in and passed to the fourth decorator
  14. How layering works: * Fourth decorator wraps all the content with a &lt;dd&gt; tag and passes the aggregate content to the fifth decorator
  15. How layering works: * Fifth decorator generates label using formLabel() view helper, and prepends it to the content; the aggregate is returned
  16. Revised SimpleInput decorator; no label generation
  17. Label decorator; only renders label
  18. Typical approach to handling placement (typically append or prepend; replace would not use this strategy)
  19. Specifying multiple decorators at instantiation
  20. Specifying alternate placement for a specific decorator
  21. Reflecting on the element in order to generate custom markup; renders the label and view helper decorators
  22. Composite markup that might not be achieved otherwise... which leads into the next topic
  23. Use the discrete value segments from the element to populate the form input