<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nitak Studio</title>
	<atom:link href="http://nitak-studio.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://nitak-studio.com/blog</link>
	<description>Web design, standards du Web et développement</description>
	<lastBuildDate>Fri, 10 Feb 2012 07:41:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/><xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Un « slug » ? Mais ça vient d’où ce truc ?</title>
		<link>http://nitak-studio.com/blog/2012/02/10/definition-slug-wordpress/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=definition-slug-wordpress</link>
		<comments>http://nitak-studio.com/blog/2012/02/10/definition-slug-wordpress/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 07:04:20 +0000</pubDate>
		<dc:creator>JB</dc:creator>
				<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[slug]]></category>
		<category><![CDATA[url rewriting]]></category>

		<guid isPermaLink="false">http://nitak-studio.com/blog/?p=62</guid>
		<description><![CDATA[Si vous avez déjà trifouillé dans le code source de WordPress vous avez sans doute remarqué l’expression que les développeurs de ce CMS ont utilisé pour nommer un texte réécrit dans une URL. Dans WordPress cela s’appelle un « slug ». En gros, un « slug » c’est un texte, par exemple « Salut l’ami » qui est transformé en son ...]]></description>
			<content:encoded><![CDATA[<p>Si vous avez déjà trifouillé dans le code source de <a href="http://wordpress.org/">WordPress</a> vous avez sans doute remarqué l’expression que les développeurs de ce CMS ont utilisé pour nommer un texte réécrit dans une URL. Dans WordPress cela s’appelle un « slug ».</p>
<p>En gros, un « slug » c’est un texte, par exemple « Salut l’ami » qui est transformé en son équivalent URL « friendly ». Ce qui donne « salut-l-ami » ou encore « salut-ami ».</p>
<p><span id="more-62"></span></p>
<p>Si vous ne connaissiez pas l’expression « slug », dans d’autres CMS ont trouve parfois des noms comme « friendy_url » ou encore « rewrote_url ». Mais si on cherche la définition ou la traduction du mot « slug » on trouve assez difficilement quelque chose de cohérent par rapport à l’utilisation qui en est faite dans WordPress.</p>
<h2>Un « slug » en imprimerie</h2>
<p>Un « slug » ça vient d’une machine d’imprimerie utilisée, principalement dans le domaine de la presse, entre 1800 et 1970 : la <a href="http://fr.wikipedia.org/wiki/Linotype">Linotype</a>. Cette machine permettait de produire des lignes de textes en plomb. Contrairement aux machines de typographie classiques de l’époque où chaque caractère était indépendant, la <a href="http://en.wikipedia.org/wiki/Linotype_machine">Linotype</a> permettait de fondre des lignes complètes de texte (plus facile et plus rapide à manipuler)</p>
<p>Ces lignes de texte s’appelaient, en français, des « ligne-bloc » et en anglais des « slug ». Voilà pour la définition originale de « slug ». On commence à y voir plus clair.</p>
<p><a href="http://nitak-studio.com/blog/wp-content/uploads/2012/02/800px-Linotype_Zeilenblock_Frontansicht.jpg"><img class="alignnone size-medium wp-image-67" title="800px-Linotype_Zeilenblock_Frontansicht" src="http://nitak-studio.com/blog/wp-content/uploads/2012/02/800px-Linotype_Zeilenblock_Frontansicht-300x38.jpg" alt="" width="300" height="38" /></a></p>
<p>En cas d’erreur (elles étaient apparemment fréquentes) dans une ligne-bloc, on devait remplacer toute la ligne. Par extension, le mot « slug » s’appliqua à l’action de remplacer les ligne-blocs par leurs versions corrigées.</p>
<h2>Un « slug » en journalisme</h2>
<p>Une autre définition qui pourrait coller à l&#8217;utilisation de l&#8217;expression « slug » dans WordPress est celle qui en faite dans le domaine du journalisme. Dans ce cas un « slug » est, parfois employé pour définir une référence à un travail.</p>
<p>Cela pourrait coller avec le fait que le « slug » dans l&#8217;URL fait référence à un article. En revanche cela fonctionne moins bien si on fait référence à des pages classiques ou a des catégories.</p>
<p>Conclusion finale : faites votre choix, ou prenez un peu des deux. :p</p>
]]></content:encoded>
			<wfw:commentRss>http://nitak-studio.com/blog/2012/02/10/definition-slug-wordpress/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Le forum Alsacreations perd son droit de vote</title>
		<link>http://nitak-studio.com/blog/2012/02/04/alsacreations-perd-son-droit-de-vote/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=alsacreations-perd-son-droit-de-vote</link>
		<comments>http://nitak-studio.com/blog/2012/02/04/alsacreations-perd-son-droit-de-vote/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 15:46:02 +0000</pubDate>
		<dc:creator>JB</dc:creator>
				<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://nitak-studio.com/blog/?p=53</guid>
		<description><![CDATA[Aujourd’hui le forum d’Alsacreations à subi une modification qui peut paraitre anodine à première vue, mais qui, à mon avis, ne l’est pas du tout. L’intégralité des liens a reçu un attribut « rel » avec la valeur « nofollow ». Le but, on s’en doute, est certainement de tenter de lutter (un peu) contre ...]]></description>
			<content:encoded><![CDATA[<p>Aujourd’hui le <a href="http://forum.alsacreations.com/">forum d’Alsacreations</a> à subi une modification qui peut paraitre anodine à première vue, mais qui, à mon avis, ne l’est pas du tout. L’intégralité des liens a reçu un attribut « rel » avec la valeur « <a href="http://fr.wikipedia.org/wiki/Nofollow">nofollow</a> ». Le but, on s’en doute, est certainement de tenter de lutter (un peu) contre le spam. Le problème de ce genre de mesures radicales c’est qu’en plus d’être peu efficaces contre le spam, elles pénalisent les bonnes ressources.</p>
<p><span id="more-53"></span></p>
<p>Je ne vais pas expliquer comment le Web fonctionne, mais juste rappeler un élément clé de notre média : le lien hypertexte. Quand je fais un lien vers une ressource c’est pour permettre à l’utilisateur d’y accéder simplement. Si cette ressource est un site externe, j’accorde, en plus, ce qu’on pourrait appeler un vote de confiance à ce site en invitant l’internaute à la visiter.</p>
<p>Ça, c’est la base du fonctionnement du Web, mais c’est aussi celle du fonctionnement de Google (et de tous les moteurs de recherche modernes, Bing, Yandex, etc.). Ce n’est bien sûr pas le seul critère, mais il reste encore aujourd’hui très important.</p>
<p>Quand je suis sur le forum et que je fais un lien vers un site, je fais un vote de confiance vers cette ressource avec la voix d’Alsacreations. Google traduit cela par : Alsacreations recommande cette ressource.</p>
<p>Le <em>nofollow</em> est une sorte de patch bancal proposé par les moteurs de recherche qui permet de supprimer cette valeur de vote positif d’un lien. Quand je fais un lien <em>nofollow</em> je dis aux moteurs de recherche : voici un lien, mais je n’accorde pas ma confiance à cette ressource donc n&#8217;en tenez pas compte.</p>
<p>Le but de <del>cette aberration</del> ce patch est de réduire le spam. Dans la pratique cela fonctionne un peu, mais pas entièrement, et surtout cela va à l’encontre de ce qu’est et de la façon dont fonctionne le Web. En fait cela sert surtout à alléger la charge de travail des éditeurs de moteurs de recherche.</p>
<p>Ce qui est vraiment dommage c’est que d’un coup tout le poids que donnait le forum Alsacreations à d’excellentes ressources vient de partir en fumée. Et dans un deuxième temps, la communauté s’est privée d’une partie de sa voix pour promouvoir les ressources de qualité.</p>
<p>Bien sûr, il s’agit de la partie réservée aux moteurs de recherche en général et à Google en particulier. Mais on sait comment fonctionne le Web actuel et les moteurs y ont une place prépondérante (et c’est bien dommage). C&#8217;est triste de voir que de très bons sites comme Alsacreations, soient contraints de recourir à des méthodes que Google et les autres moteurs imposent, de fait, car ils ne sont pas capables de lutter efficacement contre le spam. Surtout quand les méthodes causent des dommages collatéraux pour le bon Web.</p>
<p>Pourtant on pourrait essayer de trouver des parades, comme limiter le <em>nofollow</em> aux membres récemment inscrits ou participants peu (ancienneté, nombre de publications). Ou chercher d’autres pistes, mais toujours moins pénalisantes pour les ressources de qualité.</p>
]]></content:encoded>
			<wfw:commentRss>http://nitak-studio.com/blog/2012/02/04/alsacreations-perd-son-droit-de-vote/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Charger automatiquement vos classes avec __autoload</title>
		<link>http://nitak-studio.com/blog/2011/08/29/charger-automatiquement-vos-classes-avec-__autoload/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=charger-automatiquement-vos-classes-avec-__autoload</link>
		<comments>http://nitak-studio.com/blog/2011/08/29/charger-automatiquement-vos-classes-avec-__autoload/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 19:45:21 +0000</pubDate>
		<dc:creator>JB</dc:creator>
				<category><![CDATA[PHP et MySQL]]></category>

		<guid isPermaLink="false">http://nitak-studio.com/blog/?p=46</guid>
		<description><![CDATA[Pour garder une bonne organisation de ses classes, il est pratique de n&#8217;avoir qu&#8217;une seule classe par fichier. Le problème de ce genre d&#8217;organisation est qu&#8217;il faut souvent inclure de nombreux fichiers dans ses scripts. Encore pire, l&#8217;utilisation de include_once() et require_once() devient souvent obligatoire afin d&#8217;éviter les inclusions multiples. Ces deux fonctionnalités sont hélas ...]]></description>
			<content:encoded><![CDATA[<p>Pour garder une bonne organisation de ses classes, il est pratique de n&#8217;avoir qu&#8217;une seule classe par fichier. Le problème de ce genre d&#8217;organisation est qu&#8217;il faut souvent inclure de nombreux fichiers dans ses scripts. Encore pire, l&#8217;utilisation de include_once() et require_once() devient souvent obligatoire afin d&#8217;éviter les inclusions multiples. Ces deux fonctionnalités sont hélas très mauvaises pour les performances (surtout, mais pas que, si on utilise un système de cache d&#8217;opcode comme APC).</p>
<p>Heureusement, depuis la version 5 de PHP on peut définir une fonction magique nommée __autoload et qui se chargera de charger automatiquement les fichiers contenant les classes à la volée.</p>
<p><span id="more-46"></span>Pour pouvoir utiliser cette fonctionnalité, il faut avoir une certaine rigueur dans l&#8217;organisation de ses fichiers et dans la façon de nommer ses classes.</p>
<p>Voici un exemple de structure et de conventions que j&#8217;utilise pour mes sites :</p>
<p>Mes classes sont nommées en utilisant le style CamelCase majuscule. C&#8217;est-à-dire que les mots sont tous composés d&#8217;une première lettre en majuscule suive de minuscules. Les mots sont collés les uns aux autres. Exemples : MaClasse, Database, Pdf&#8230; .</p>
<p>Mes noms de fichiers contenant des classes sont composés uniquement de lettres minuscules et les mots sont séparés par des tirets-bas. Le nom du fichier se termine par le suffixe : &laquo;&nbsp;.class.php&nbsp;&raquo;. Exemples : ma_classe.class.php, database.class.php, pdf.class.php&#8230; .</p>
<p>Mes scripts PHP sont stockés dans un dossier nommé &laquo;&nbsp;core&nbsp;&raquo;. Une constante CORE_DIR est définie et contient le chemin absolu vers ce dossier.</p>
<p>Mes classes sont stockées dans trois sous dossiers contenus dans &laquo;&nbsp;core&nbsp;&raquo; :</p>
<ul>
<li>&laquo;&nbsp;libs&nbsp;&raquo; pour les classes génériques</li>
<li>&laquo;&nbsp;controllers&nbsp;&raquo; pour les contrôleurs</li>
<li>&laquo;&nbsp;models&nbsp;&raquo; pour les modèles</li>
</ul>
<p>Ma fonction __autoload devra donc effectuer les opérations suivantes :</p>
<ul>
<li>Faire la correspondance entre le nom de la classe et le nom du fichier. MaClasse devient ma_classe.class.php</li>
<li>Vérifier si le fichier existe dans les 3 dossiers, l&#8217;un après l&#8217;autre.</li>
<li>Si le fichier est trouvé, l&#8217;inclure et renvoyer un booléen.</li>
</ul>
<p>La fonction __autoload prend en argument le nom de la classe appelée. Elle doit renvoyer un booléen : TRUE si le fichier a été trouvé et inclut, FALSE dans le cas contraire.</p>
<p>Et voici le code de notre fonction __autoload correspondant à nos besoins :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> __autoload<span style="color: #009900;">&#40;</span><span style="color: #000088;">$class_name</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #666666; font-style: italic;">// on converti le nom de la classe en nom de fichier.</span>
 <span style="color: #000088;">$base_name</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strtolower</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/(?&amp;lt;=[a-z])(?=[A-Z])/'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'_'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$class_name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000088;">$file_name</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$base_name</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'.class.php'</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #666666; font-style: italic;">// un tableau contenant nos chemins dans l'ordre dans lequel on veut les tester</span>
 <span style="color: #000088;">$paths</span> <span style="color: #339933;">=</span> <span style="color: #990000;">Array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000088;">$paths</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> CORE_DIR <span style="color: #339933;">.</span> <span style="color: #0000ff;">'libs/'</span><span style="color: #339933;">;</span>
 <span style="color: #000088;">$paths</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> CORE_DIR <span style="color: #339933;">.</span> <span style="color: #0000ff;">'controllers/'</span><span style="color: #339933;">;</span>
 <span style="color: #000088;">$paths</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> CORE_DIR <span style="color: #339933;">.</span> <span style="color: #0000ff;">'models/'</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #009933; font-style: italic;">/**
  * On teste si le fichier existe dans nos dossiers,
  * si le fichier existe, on l'inclut et on quitte la fonction
  * en renvoyant le booléen TRUE.
   */</span>
 <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$paths</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$path</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">file_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$path</span><span style="color: #339933;">.</span><span style="color: #000088;">$file_name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #b1b100;">require</span> <span style="color: #000088;">$path</span><span style="color: #339933;">.</span><span style="color: #000088;">$file_name</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">TRUE</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #009933; font-style: italic;">/**
  * Si le fichier n'a pas été trouvé, on quitte la fonction
  * en renvoyant le booléen FALSE.
   */</span>
 <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">FALSE</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Il suffit d&#8217;inclure cette fonction dans un fichier commun à nos scripts et elle sera exécutée automatiquement quand on tentera d&#8217;instancier une classe qui n&#8217;est pas déclarée.</p>
]]></content:encoded>
			<wfw:commentRss>http://nitak-studio.com/blog/2011/08/29/charger-automatiquement-vos-classes-avec-__autoload/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Gérer la connexion à la base de données avec le patron de conception Singleton</title>
		<link>http://nitak-studio.com/blog/2011/08/22/gerer-la-connexion-a-la-base-de-donnees-avec-le-patron-de-conception-singleton/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=gerer-la-connexion-a-la-base-de-donnees-avec-le-patron-de-conception-singleton</link>
		<comments>http://nitak-studio.com/blog/2011/08/22/gerer-la-connexion-a-la-base-de-donnees-avec-le-patron-de-conception-singleton/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 20:41:03 +0000</pubDate>
		<dc:creator>JB</dc:creator>
				<category><![CDATA[PHP et MySQL]]></category>

		<guid isPermaLink="false">http://nitak-studio.com/blog/?p=38</guid>
		<description><![CDATA[En programmation orientée objet, le motif Singleton permet d&#8217;être sûr qu&#8217;une classe ne sera instanciée qu&#8217;une seule fois. À chaque fois que l&#8217;on fera appel à cette classe, nous récupérerons l&#8217;unique instance de cette dernière. Dans le cadre d&#8217;une connexion à la base de données, ce motif est très pratique, car nous sommes certains de ...]]></description>
			<content:encoded><![CDATA[<p>En programmation orientée objet, le motif Singleton permet d&#8217;être sûr qu&#8217;une classe ne sera instanciée qu&#8217;une seule fois. À chaque fois que l&#8217;on fera appel à cette classe, nous récupérerons l&#8217;unique instance de cette dernière.</p>
<p>Dans le cadre d&#8217;une connexion à la base de données, ce motif est très pratique, car nous sommes certains de récupérer la connexion courante et de ne pas en créer une à chaque fois.</p>
<p><span id="more-38"></span></p>
<h3>Principe du motif Singleton</h3>
<p>Le Singleton est l&#8217;un des patrons de conception que l&#8217;on apprend en général au début de son apprentissage de la programmation orientée objet, car il est très facile à comprendre.</p>
<h4>Le principe est le suivant :</h4>
<ul>
<li>Une classe Singleton aura une instance unique quoiqu&#8217;il arrive.</li>
<li>Quand on appellera cette classe, nous recevrons à chaque fois cette unique instance.</li>
<li>Il n&#8217;est pas possible d&#8217;instancier manuellement ni de cloner une classe Singleton.</li>
</ul>
<h4>En programmation cela se traduit par :</h4>
<ul>
<li>Le constructeur est privé afin que l&#8217;on ne puisse pas instancier l&#8217;objet.</li>
<li>Le cloneur est privé afin que l&#8217;on ne puisse pas cloner l&#8217;objet.</li>
<li>L&#8217;unique instance de la classe est contenue dans la classe elle même.</li>
<li>Quand on demande à récupérer l&#8217;instance de la classe, elle est créée si elle n&#8217;existe pas, puis elle est renvoyée.</li>
</ul>
<h4>Exemple en PHP :</h4>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Singleton <span style="color: #009900;">&#123;</span>
&nbsp;
 <span style="color: #009933; font-style: italic;">/**
   * @var Singleton
   * @access private
   * @static
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> static <span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">NULL</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Le constructeur est privé pour qu'on ne puisse
   * pas instancier la classe depuis l'extérieur
   *
   * @access private
   * @param void
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// constructeur privé</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Le cloneur est privé pour qu'on ne puisse pas cloner l'objet
   *
   * @access private
   * @param void
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __clone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// cloneur privé</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Méthode qui crée l'unique instance de la classe
   * si elle n'existe pas puis la renvoie.
   *
   * @access public
   * @static
   * @param void
   * @return Singleton object
   */</span>
   <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> getInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">NULL</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
     <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Méthode qui détruit l'unique instance de la classe.
   *
   * @access public
   * @static
   * @param void
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> killInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">NULL</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h4>Voici comment on utilisera cette classe :</h4>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// on crée ou récupère l'objet Singleton</span>
<span style="color: #000088;">$singleton</span> <span style="color: #339933;">=</span> Singleton<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// $singleton est un objet représentant l'unique instance de la classe Singleton.</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// on détruit l'objet Singleton</span>
<span style="color: #000088;">$singleton</span> <span style="color: #339933;">=</span> Singleton<span style="color: #339933;">::</span><span style="color: #004000;">killInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>On imagine bien le côté pratique pour la gestion d&#8217;une connexion à une base de données. Quand on demande l&#8217;instance de l&#8217;objet on vérifie si l&#8217;objet mysqli ou PDO existe, si ce n&#8217;est pas le cas on le crée en se connectant à la base de données et enfin on renvoi l&#8217;objet (et donc l&#8217;unique connexion). Si on souhaite couper la connexion explicitement il suffit d&#8217;appeler la méthode killInstance().</p>
<p>Néanmoins il existe une limite avec ce système : si le site utilise plusieurs bases de données et que l&#8217;on souhaite les utiliser au cours d&#8217;un même script on ne pourra pas le faire. Pour pallier à ce problème, il existe une variante du Singleton qu&#8217;on appelle le Multiton.</p>
<h3>Variante : le Multiton</h3>
<p>On ne peut pas dire que le Multiton soit un patron de conception différent du Singleton, c&#8217;est en fait une variante qui permet tout simplement de travailler avec plusieurs instances uniques d&#8217;un objet Singleton.</p>
<p>Dans le cadre d&#8217;une utilisation avec une base de données cela permet de gérer plusieurs connexions tout en étant sûr que chaque connexion sera elle même unique quoiqu&#8217;il arrive.</p>
<h4>Ce qui donne en PHP :</h4>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Multiton <span style="color: #009900;">&#123;</span>
&nbsp;
 <span style="color: #009933; font-style: italic;">/**
   * @var Multiton
   * @access private
   * @static
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> static <span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #990000;">Array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Le constructeur est privé pour qu'on ne puisse
   * pas instancier la classe depuis l'extérieur
   *
   * @access private
   * @param void
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// constructeur privé</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Le cloneur est privé pour qu'on ne puisse pas cloner l'objet
   *
   * @access private
   * @param void
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __clone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// cloneur privé</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Méthode qui crée une instance unique si elle n'existe pas puis la renvoie.
   *
   * @access public
   * @static
   * @param string $id
   * @return Multiton object
   */</span>
   <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> getInstance<span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Multiton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
     <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Méthode qui détruit l'instance.
   *
   * @access public
   * @static
   * @param string $id
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> killInstance<span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #990000;">unset</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h4>Voici comment on utilisera cette classe :</h4>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// on crée ou récupère une instance</span>
<span style="color: #000088;">$un_id</span> <span style="color: #339933;">=</span> Singleton<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'un_id'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// $un_id est un objet representant une instance unique de la classe.</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// on crée ou récupère une autre instance</span>
<span style="color: #000088;">$un_autre_id</span> <span style="color: #339933;">=</span> Singleton<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'un_autre_id'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// $un_autre_id est un objet representant une autre instance unique de la classe.</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// on détruit une des instances</span>
<span style="color: #000088;">$singleton</span> <span style="color: #339933;">=</span> Singleton<span style="color: #339933;">::</span><span style="color: #004000;">killInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'un_id'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h3>Cas pratique pour la connexion à une base de données</h3>
<p>Nous allons maintenant voir comment implémenter ce motif avec le cas pratique de la gestion de la connexion à une ou plusieurs bases de données. Pour l&#8217;exemple j&#8217;utilise l&#8217;API PDO pour gérer ma connexion.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/**
 * Db class
 */</span>
<span style="color: #000000; font-weight: bold;">class</span> Db <span style="color: #009900;">&#123;</span>
&nbsp;
 <span style="color: #009933; font-style: italic;">/**
   * @var Db
   * @access private
   * @static
   */</span>
 <span style="color: #000000; font-weight: bold;">private</span> static <span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #990000;">Array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Le constructeur est privé pour qu'on ne puisse
   * pas instancier la classe depuis l'extérieur
   *
   * @access private
   * @param void
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// constructeur privé</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Le cloneur est privé pour qu'on ne puisse pas cloner l'objet
   *
   * @access private
   * @param void
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __clone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// cloneur privé</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Méthode qui crée une instance unique si elle n'existe pas puis la renvoie.
   *
   * @access public
   * @static
   * @param string $id
   * @return Db object
   */</span>
 <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> getInstance<span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'default'</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #000088;">$config</span> <span style="color: #339933;">=</span> Config<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000088;">$db_config</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$config</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>get<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'database'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$db_config</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">FALSE</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">__CLASS__</span><span style="color: #339933;">.</span><span style="color: #0000ff;">': Database configuration no found: &quot;'</span><span style="color: #339933;">.</span><span style="color: #000088;">$id</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'&quot;.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000088;">$dsn</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$databases</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'driver'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">':host='</span><span style="color: #339933;">.</span><span style="color: #000088;">$databases</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'host'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">';dbname='</span><span style="color: #339933;">.</span><span style="color: #000088;">$databases</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$databases</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'user'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$password</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$databases</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'password'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    try <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> PDO<span style="color: #009900;">&#40;</span><span style="color: #000088;">$dsn</span><span style="color: #339933;">,</span> <span style="color: #000088;">$user</span><span style="color: #339933;">,</span> <span style="color: #000088;">$password</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>PDO<span style="color: #339933;">::</span><span style="color: #004000;">MYSQL_ATTR_INIT_COMMAND</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">&quot;SET NAMES 'UTF8'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setAttribute<span style="color: #009900;">&#40;</span>PDO<span style="color: #339933;">::</span><span style="color: #004000;">ATTR_ERRMODE</span><span style="color: #339933;">,</span> PDO<span style="color: #339933;">::</span><span style="color: #004000;">ERRMODE_EXCEPTION</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>PDOException <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Erreur de connexion à la base de données.
Vous pouvez essayer de rafraîchir la page.
'</span><span style="color: #339933;">.</span><span style="color: #000088;">$e</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getMessage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * Méthode qui détruit l'instance.
   *
   * @access public
   * @static
   * @param string $id
   * @return void
   */</span>
   <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> killInstance<span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'default'</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
     <span style="color: #990000;">unset</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h4>Et voici comment on l&#8217;utilise :</h4>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// on se connecte ou on récupère la connexion à la base de données &quot;default&quot;</span>
<span style="color: #000088;">$db</span> <span style="color: #339933;">=</span> Db<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// on se connecte ou on récupère la connexion à la base de données &quot;chat&quot;</span>
<span style="color: #000088;">$db_chat</span> <span style="color: #339933;">=</span> Db<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'chat'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// on ferme explicitement la connexion à la base de données &quot;default&quot;</span>
Db<span style="color: #339933;">::</span><span style="color: #004000;">killInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// on ferme explicitement la connexion à la base de données &quot;chat&quot;</span>
Db<span style="color: #339933;">::</span><span style="color: #004000;">killInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'chat'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Vous aurez remarqué que je fais appel à un objet $config pour récupérer la configuration de la base de données. Cet objet est un simple Singleton qui me permet d&#8217;accéder à la configuration de mon site depuis mes scripts sans utiliser de constantes ou de variables globales.</p>
<p>Pour voir si vous avez bien compris le principe vous pourriez essayer d&#8217;implémenter vous même la classe Singleton Config.</p>
]]></content:encoded>
			<wfw:commentRss>http://nitak-studio.com/blog/2011/08/22/gerer-la-connexion-a-la-base-de-donnees-avec-le-patron-de-conception-singleton/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quelle extension choisir entre mysql, mysqli et PDO ?</title>
		<link>http://nitak-studio.com/blog/2011/08/22/quelle-extension-choisir-entre-mysql-mysqli-et-pdo/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=quelle-extension-choisir-entre-mysql-mysqli-et-pdo</link>
		<comments>http://nitak-studio.com/blog/2011/08/22/quelle-extension-choisir-entre-mysql-mysqli-et-pdo/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 18:32:29 +0000</pubDate>
		<dc:creator>JB</dc:creator>
				<category><![CDATA[PHP et MySQL]]></category>

		<guid isPermaLink="false">http://nitak-studio.com/blog/?p=29</guid>
		<description><![CDATA[PHP dispose de 3 API permettant de communiquer avec MySQL : l&#8217;historique mysql (PHP 4.x et moins), mysqli (PHP 5.x) et PDO (PHP 5.x). Quels sont les avantages et les inconvénients de chacune d&#8217;elle et laquelle doit-on utiliser dans ses scripts ? L&#8217;extension mysql Tout d&#8217;abord, parlons un peu de l&#8217;extension originale mysql. C&#8217;est la ...]]></description>
			<content:encoded><![CDATA[<p>PHP dispose de 3 API permettant de communiquer avec MySQL : l&#8217;historique mysql (PHP 4.x et moins), mysqli (PHP 5.x) et PDO (PHP 5.x).</p>
<p>Quels sont les avantages et les inconvénients de chacune d&#8217;elle et laquelle doit-on utiliser dans ses scripts ?</p>
<p><span id="more-29"></span></p>
<h4>L&#8217;extension mysql</h4>
<p>Tout d&#8217;abord, parlons un peu de l&#8217;extension originale mysql. C&#8217;est la plus connue et on la retrouve, hélas, dans de nombreux scripts disponibles sur le Web.</p>
<p>De nombreux débutants l&#8217;utilisent encore en 2011, ce qui est une vraie erreur. En effet cette extension n&#8217;est incluse la distribution PHP que pour des raisons de compatibilité avec les anciens scripts. Elle n&#8217;est plus développée depuis la sortie de PHP 5.0 en 2004. Les seules modifications apportées à cette extension sont des opérations de maintenance, par exemple la correction de failles de sécurité.</p>
<p>De plus cette extension ne supporte que les spécificités de MySQL versions 4.1 et inférieures (pour rappel, à la date où j&#8217;écris cet article nous sommes à la version 5.6 de MySQL). En fait la seule raison d&#8217;utiliser aujourd&#8217;hui cette extension serait d&#8217;hériter d&#8217;un vieux projet tournant sous PHP 4.x ou moins et dont on ne pourrait pas mettre à jour la version de PHP.</p>
<h4>L&#8217;extension mysqli</h4>
<p>Le &laquo;&nbsp;i&nbsp;&raquo; signifie &laquo;&nbsp;improved&nbsp;&raquo; (amélioré) et explique bien ce qu&#8217;est cette extension : une version améliorée de l&#8217;ancienne extension mysql. Mysqli est disponible depuis PHP 5.0 et est l&#8217;extension par défaut pour les versions récentes de PHP.</p>
<p>Cette API supporte les spécificités des versions supérieures à 4.1 de MySQL et possède de nombreux avantages par rapport a l&#8217;ancienne extension mysql :</p>
<ul>
<li>Interface au choix orientée objet ou procédurale</li>
<li>Support des requêtes préparées</li>
<li>Support des commandes multiples</li>
<li>Support des Transactions</li>
<li>Capacités de débogage avancées</li>
<li>Support du serveur embarqué</li>
</ul>
<p>Mysqli est construite pour travailler en mode orienté objet. Si vous vous lancez dans un nouveau projet utilisant cette API c&#8217;est un bon choix de travailler dans ce mode. Néanmoins elle autorise de travailler en mode procédural comme avec l&#8217;ancienne API mysql. Cela peut être pratique pour 2 raisons :</p>
<ul>
<li>On peut facilement convertir un projet utilisant l&#8217;ancienne mysql pour travailler avec mysqli, pour cela il suffit dans la plupart des cas des simplement changer le nom des fonctions mysql_* par mysqli_*. Et c&#8217;est tout.</li>
<li>Si on n&#8217;est pas habitué à la programmation orientée objet ou si on ne souhaite tout simplement pas l&#8217;utiliser, alors on peut travailler avec mysqli en mode procédural.</li>
</ul>
<p>D&#8217;après la documentation officielle de PHP, cette extension est celle à préférer lorsqu&#8217;on souhaite développer un nouveau projet utilisant MySQL (voir tableau comparatif à la fin de l&#8217;article).</p>
<p>Pour aller plus loin reportez-vous à la <a href="http://www.php.net/manual/fr/book.mysqli.php" target="_blank">documentation officielle de mysqli</a>.</p>
<h4>L&#8217;extension PDO</h4>
<p>L&#8217;abréviation PDO signifie PHP Data Object. Il s&#8217;agit d&#8217;une couche d&#8217;abstraction de base de données. En clair PDO permet de travailler avec MySQL mais aussi avec de nombreux autres gestionnaires de bases de données. L&#8217;avantage est que vous apprenez les commandes PDO et si vous devez travailler un jour sur un projet utilisant un autre moteur de base de données que MySQL vous n&#8217;avez pas à réapprendre de nouvelles commandes.</p>
<p>PDO gère automatiquement les différences entre les différents types de bases de données de façon transparente. Cela signifie que si vous utilisez une fonction PDO qui n&#8217;est pas supportée par votre moteur de base de données, PDO se chargera d&#8217;émuler la fonctionnalité de manière transparente.</p>
<p>L&#8217;utilisation de PDO se fait en mode orienté objet et il est très simple à utiliser. De plus cette API supporte la plupart des spécificités des versions modernes de MySQL (mais moins que mysqli).</p>
<p>Pour aller plus loin reportez-vous à la <a href="http://www.php.net/manual/fr/book.pdo.php" target="_blank">documentation officielle de PDO</a>.</p>
<h4>Comparatif des 3 extensions</h4>
<p>Voici un tableau comparant mysql, mysqli et PDO et tiré de la documentation officielle de PHP :</p>
<table class="doctable informaltable">
<colgroup>
<col width="50" align="left" />
<col width="50" align="left" />
<col width="50" align="left" />
<col width="50" align="left" /> </colgroup>
<thead valign="middle">
<tr valign="middle">
<th class="empty"></th>
<th>Extension mysqli</th>
<th>PDO (avec le pilote PDO MySQL Driver et MySQL Native Driver)</th>
<th>Extension MySQL</th>
</tr>
</thead>
<tbody class="tbody" valign="middle">
<tr valign="middle">
<td align="left">Version d&#8217;introduction en PHP</td>
<td align="left">5.0</td>
<td align="left">5.0</td>
<td align="left">Avant 3.0</td>
</tr>
<tr valign="middle">
<td align="left">Inclus en PHP 5.x</td>
<td align="left">Oui</td>
<td align="left">Oui</td>
<td align="left">Oui</td>
</tr>
<tr valign="middle">
<td align="left">Statut de développement MySQL</td>
<td align="left">Développement actif</td>
<td align="left">Développement actif depuis PHP 5.3</td>
<td align="left">Maintenance uniquement</td>
</tr>
<tr valign="middle">
<td align="left">Recommandée pour les nouveaux projets MySQL</td>
<td align="left">Oui, et préférée</td>
<td align="left">Oui</td>
<td align="left">Non</td>
</tr>
<tr valign="middle">
<td align="left">L&#8217;API supporte les jeux de caractères</td>
<td align="left">Oui</td>
<td align="left">Oui</td>
<td align="left">Non</td>
</tr>
<tr valign="middle">
<td align="left">L&#8217;API supporte les commandes préparées</td>
<td align="left">Oui</td>
<td align="left">Oui</td>
<td align="left">Non</td>
</tr>
<tr valign="middle">
<td align="left">L&#8217;API supporte les commandes préparées coté client</td>
<td align="left">Non</td>
<td align="left">Oui</td>
<td align="left">Non</td>
</tr>
<tr valign="middle">
<td align="left">L&#8217;API supporte les procédures stockées</td>
<td align="left">Oui</td>
<td align="left">Oui</td>
<td align="left">Non</td>
</tr>
<tr valign="middle">
<td align="left">L&#8217;API supporte les commandes multiples</td>
<td align="left">Oui</td>
<td align="left">La plupart</td>
<td align="left">Non</td>
</tr>
<tr valign="middle">
<td align="left">Toutes toutes les fonctionnalités MySQL 4.1 et plus récent</td>
<td align="left">Oui</td>
<td align="left">La plupart</td>
<td align="left">Non</td>
</tr>
</tbody>
</table>
<h4>Conclusion</h4>
<p>Oubliez l&#8217;obsolète extension mysql, elle ne permet pas de travailler correctement avec les versions récentes de MySQL et n&#8217;est présente que pour des raisons de compatibilité.</p>
<p>Préférez lui mysqli ou PDO. Selon vos goûts et vos besoins.</p>
]]></content:encoded>
			<wfw:commentRss>http://nitak-studio.com/blog/2011/08/22/quelle-extension-choisir-entre-mysql-mysqli-et-pdo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comment utiliser le codage UTF-8 avec PHP et MySQL</title>
		<link>http://nitak-studio.com/blog/2011/08/21/comment-utiliser-le-codage-utf-8-avec-php-et-mysql/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=comment-utiliser-le-codage-utf-8-avec-php-et-mysql</link>
		<comments>http://nitak-studio.com/blog/2011/08/21/comment-utiliser-le-codage-utf-8-avec-php-et-mysql/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 16:18:00 +0000</pubDate>
		<dc:creator>JB</dc:creator>
				<category><![CDATA[PHP et MySQL]]></category>

		<guid isPermaLink="false">http://nitak-studio.com/blog/?p=14</guid>
		<description><![CDATA[Le codage UTF-8 est, depuis quelques années, le plus utilisé dans le monde des applications Web. Bien que simple à utiliser, il pose souvent problème aux débutants. Nous allons donc voir comment l&#8217;utiliser pour la réalisation d&#8217;un site Web. La configuration logicielle sous laquelle fonctionnera notre site sera le classique trio : Apache pour le ...]]></description>
			<content:encoded><![CDATA[<p>Le codage UTF-8 est, depuis quelques années, le plus utilisé dans le monde des applications Web.</p>
<p>Bien que simple à utiliser, il pose souvent problème aux débutants. Nous allons donc voir comment l&#8217;utiliser pour la réalisation d&#8217;un site Web.<br />
<span id="more-14"></span><br />
La configuration logicielle sous laquelle fonctionnera notre site sera le classique trio :</p>
<ul>
<li>Apache pour le serveur HTTP.</li>
<li>PHP 5.x comme langage de script.</li>
<li>MySQL 5.x pour le gestionnaire de bases de données.</li>
</ul>
<p>Pour utiliser UTF-8 sans problème avec cet environnement, il suffit de suivre ces quelques règles :</p>
<ul>
<li>Les fichiers du site doivent être codés en UTF-8.</li>
<li>Les entêtes définissant l&#8217;encodage des caractères comme étant de l&#8217;UTF-8 doivent être envoyés au client.</li>
<li>La base de données doit être codée et déclarée en UTF-8.</li>
<li>Certaines fonctions de PHP ne supportant pas l&#8217;UTF-8 doivent être abandonnées au profit de leurs équivalents supportant ce format.</li>
<li>Il faut s&#8217;assurer que les données externes utilisées par le site sont bien codées en UTF-8 et dans le cas contraire les convertir.</li>
</ul>
<h3>Encodage des fichiers</h3>
<p>La première étape pour utiliser le codage UTF-8 est d&#8217;être sûr que les fichiers du site sont bien encodés dans ce format. Pour cela, il faut utiliser un éditeur de texte ou un IDE qui le supporte correctement. À l&#8217;heure actuelle, ce n&#8217;est plus un problème, car tous les éditeurs modernes supportent correctement l&#8217;UTF-8.</p>
<h4>Avec ou sans BOM ?</h4>
<p>Le BOM (Byte Order Mark) est un caractère qui peut être utilisé pour spécifier qu&#8217;un fichier est encodé en UTF-8. Il est écrit automatiquement par votre éditeur de texte au tout début du fichier. Quand il est utilisé, l&#8217;éditeur de texte reconnaitra automatiquement que le fichier est encodé en UTF-8 et le traitera comme tel.</p>
<p>Un problème peut survenir quand des fichiers enregistrés avec BOM sont utilisés avec PHP. Ce problème survient quand on inclut des fichiers avec les directives include, include_once, require ou require_once. Dans ces cas le BOM des fichiers inclus est envoyé sur la sortie ce qui casse le fonctionnement des fonctions d&#8217;envoi d&#8217;entêtes, des cookies ainsi que des sessions.</p>
<p>La solution à ce problème est très simple : il suffit de configurer votre éditeur pour enregistrer les fichiers UTF-8 sans BOM.</p>
<p>Si vous vous retrouvez dans vos scripts avec une erreur PHP du type : &laquo;&nbsp;Headers already sent&#8230;&nbsp;&raquo;, vérifiez bien que tous vos fichiers sont bien enregistrés sans BOM.</p>
<p>Néanmoins il peut exister un petit problème avec quand on utilise des fichiers sans BOM. Si vous avez un fichier qui ne contient que des caractères contenus dans la table de caractères US-ASCII votre éditeur n&#8217;aura aucun moyen de faire la différence avec de l&#8217;UTF-8 car ce dernier est rétro compatible avec le standard ASCII. Ce qui peut arriver c&#8217;est que plus tard vous éditez votre fichier et vous saisissez des caractères spécifiques à l&#8217;UTF-8. Quand vous sauvegardez votre fichier, l&#8217;éditeur l&#8217;enregistrera dans le codage par défaut, et si ce dernier n&#8217;est pas de l&#8217;UTF-8 alors vous aurez des erreurs à l&#8217;affichage de ces nouveaux caractères.</p>
<p>Il existe 2 solutions simples pour corriger ce problème :</p>
<p>Vous configurez votre éditeur pour qu&#8217;il enregistre toujours les fichiers en UTF-8. Ce qui n&#8217;est pas toujours possible.</p>
<p>Vous faites en sorte que vos fichiers contiennent toujours au moins un caractère UTF-8. Par exemple le caractère &laquo;&nbsp;é&nbsp;&raquo;. Pour vos fichiers PHP c&#8217;est très facile à mettre en place, il suffit de rajouter ce caractère dans un commentaire au début de chaque fichier : &lt;?php /* force utf-8: é */ ?&gt;.</p>
<h3>Les entêtes UTF-8</h3>
<p>Pour que le client (en général un navigateur Web) reconnaisse à coup sûr les données qu&#8217;il reçoit comme étant codé en UTF-8 il faut lui envoyer des entêtes déclarant ce codage.</p>
<h4>L&#8217;entête HTTP</h4>
<p>Pour envoyer l&#8217;entête HTTP vous avez 2 possibilités : l&#8217;envoyer depuis le script PHP ou l&#8217;envoyer depuis le serveur HTTP (Apache). Pour être sûr que votre script soit portable d&#8217;une configuration à une autre ce n&#8217;est pas un mal de toujours envoyer l&#8217;entête depuis PHP.</p>
<p>Pour envoyer l&#8217;entête depuis votre script PHP il suffit d&#8217;ajouter la ligne suivante au tout début de votre script (avant l&#8217;affichage de n&#8217;importe quel caractère) :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Content-type: text/html; charset=UTF-8'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Si vous avez un script commun inclus à toutes vos pages, il est judicieux de placer ce code au début de script.</p>
<p>Si vous envoyez des emails depuis un script PHP, pensez aussi à déclarer le jeu de caractères UTF-8 dans l&#8217;entête des emails.</p>
<p>Si vous souhaitez laisser le serveur envoyer l&#8217;entête UTF-8 vous pouvez définir ce codage comment étant celui par défaut. Ajoutez simplement la directive suivante dans votre fichier de configuration (httpd.conf) ou dans votre fichier .htaccess :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">AddDefaultCharset UTF<span style="color: #339933;">-</span><span style="color: #cc66cc;">8</span></pre></div></div>

<h4>L&#8217;entête HTML</h4>
<p>Vos fichiers HTML doivent aussi être déclarés en UTF-8. Pour cela c&#8217;est très simple, ajoutez simplement la balise meta suivante entre &lt;head&gt; et &lt;/head&gt; :</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;</pre></div></div>

<p>Oui si vous utilisez le Doctype HTML 5 :</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;meta charset=&quot;utf-8&quot;&gt;</pre></div></div>

<h3>Utiliser de l&#8217;UTF-8 dans vos scripts PHP</h3>
<p>PHP 5.x ne travaillent pas avec le standard Unicode, il ne supporte pas nativement le traitement de chaines de caractères UTF-8. Ces fonctions supportant uniquement les caractères codés sur un octet et UTF-8 permettant de coder les caractères sur un nombre variable d&#8217;octets, elles ne fonctionneront pas correctement.</p>
<p>Par exemple le caractère “é” est encodé sur 2 octets en UTF-8. Si nous testons avec la fonction strlen() (qui renvoi le nombre de caractères d&#8217;une chaine) nous aurons un résultat erroné :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">echo</span> <span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;é&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// affiche 2</span></pre></div></div>

<p>Par chance PHP dispose d&#8217;une extension officielle (donc incluse par défaut dans l&#8217;installation de PHP) qui supporte les caractères codés sur un nombre d&#8217;octets variable. Il s&#8217;agit de l&#8217;extension mbstring.</p>
<p>L&#8217;utilisation de cette extension est extrêmement simple puisque qu&#8217;elle ne fait rien de plus qu&#8217;implémenter des équivalents multioctet des fonctions de manipulation de chaines natives de PHP.</p>
<p>La seule chose à faire et de préfixer les fonctions natives par &laquo;&nbsp;mb_&nbsp;&raquo;.</p>
<p>Exemple:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$text</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// devient :</span>
<span style="color: #990000;">mb_strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$text</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>La liste des fonctions à utiliser en place des fonctions natives de PHP est disponible sur la documentation officielle :</p>
<p>http://fr.php.net/manual/en/book.mbstring.php</p>
<p>Il suffit ensuite de déclarer à l&#8217;extension mbstring que vous souhaitez travailler en UTF-8. Pour cela il suffit de rajouter la ligne suivante dans le script commun à toutes vos pages :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">mb_internal_encoding</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'UTF-8'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>NOTE : mbstring contient des versions multioctet des fonctions ereg/eregi. L&#8217;utilisation de ces dernières n&#8217;est pas recommandée, car leurs équivalents natifs sont dépréciés en PHP 5. Donc utilisez les fonctions preg natives, car elles supportent bien l&#8217;UTF-8.</p>
<h3>UTF-8 avec MySQL</h3>
<p>Quand on veut travailler en UTF-8 avec MySQL il faut observer plusieurs points :</p>
<h4>Encodage des données dans la base</h4>
<p>Vos bases de données, tables et colonnes doivent être déclarées en UTF-8. Vous devez déclarer le jeu de caractères et la collation qui correspond.</p>
<p>En général, on utilisera le jeu de caractères utf8 et la collation utf8_general_ci. Utf8_general_ci est une collation rapide et suffisante pour la plupart des cas. Pour voir en détail les autres types de collations, reportez-vous à la documentation de MySQL.</p>

<div class="wp_syntax"><div class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">CREATE</span> <span style="color: #990099; font-weight: bold;">DATABASE</span> <span style="color: #008000;">`ma<span style="color: #008080; font-weight: bold;">_</span>base`</span> <span style="color: #990099; font-weight: bold;">DEFAULT</span> CHARACTER <span style="color: #990099; font-weight: bold;">SET</span> utf8 <span style="color: #CC0099; font-weight: bold;">COLLATE</span> utf8_general_ci<span style="color: #000033;">;</span></pre></div></div>

<h4>Déclarer le jeu de caractères lors de la connexion</h4>
<p>Quand vous vous connectez à votre base de données, la première chose à faire et de déclarer le jeu de caractères comme étant de l&#8217;UTF-8.</p>
<p>Si vous utilisez l&#8217;extension mysqli il vous suffit d&#8217;exécuter cette fonction juste après la connexion à la base de données :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">mysqli_set_charset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$link</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'utf8'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// procédural</span>
&nbsp;
<span style="color: #000088;">$mysqli</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>set_charset<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'utf8'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// orienté objet</span></pre></div></div>

<p>Si vous utilisez PDO, il n&#8217;y a pas de fonction équivalente, donc il vous suffit d&#8217;exécuter la requête suivante juste après la connexion à la base de données :</p>

<div class="wp_syntax"><div class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">SET</span> NAMES <span style="color: #008000;">'utf8'</span><span style="color: #000033;">;</span></pre></div></div>

<p>NOTE : Si vous utilisez l&#8217;extension mysql vous devriez penser à mettre à jour vos scripts pour utiliser au moins mysqli.</p>
<h3>Travailler avec des données externes</h3>
<p>Parfois vous devez travailler avec des données provenant de l&#8217;extérieur et sur lesquelles vous n&#8217;avez pas de contrôle.</p>
<p>Par exemple :</p>
<ul>
<li>Des flux RSS, Json ou XML</li>
<li>Des fichiers</li>
<li>Des bases de données distantes</li>
</ul>
<p>Quand vous recevez ces données, vous devez vérifier si elles sont bien encodées en UTF-8 et si ce n&#8217;est pas le cas les convertir dans ce jeu de caractères.</p>
<p>Pour déterminer si des données sont encodées en UTF-8 vous pouvez utiliser la fonction mb_detect_encoding() de l&#8217;extension mbstring :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">mb_detect_encoding</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'UTF-8'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'UTF-8'</span><span style="color: #009900;">&#41;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;C'est bien de l'UTF-8&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">else</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Ce n'est pas de l'UTF-8&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Si les données sont bien en UTF-8 vous pouvez les utiliser directement sur votre site. Sinon il vous suffit de les convertir avec la fonction mb_convert_encoding().</p>
<p>Vous pouvez aussi regarder les fonctions utf8_encode() et utf8_decode() qui permettent respectivement d&#8217;encoder et décoder UTF-8 de et vers le jeu de caractères ISO-8859-1.</p>
<h3>Repérer et corriger les erreurs d&#8217;affichage des caractères</h3>
<p>Il existe 2 cas de figure classiques :</p>
<h4>Les caractères accentués sont remplacés par des caractères du genre : Ã©, Ã, etc :</h4>
<p>Problème :</p>
<p>Vos données sont bien encodées en UTF-8 mais le navigateur tente de les afficher en ISO-8859-1.</p>
<p>Solutions :</p>
<ul>
<li>Vérifiez que vous envoyez bien l&#8217;entête HTTP pour déclarer les données en UTF-8.</li>
<li>Vérifiez que le jeu de caractères est bien déclaré en UTF-8 dans votre entête HTML (meta charset).</li>
<li>Vérifiez que vous avez bien déclaré le jeu de caractères après la connexion à la base de données (SET NAME).</li>
</ul>
<h4>Les caractères accentués sont remplacés par des losanges contenant un point d&#8217;interrogation :</h4>
<p>Problème :</p>
<p>Vos données sont encodées en ISO-8859-1 mais le navigateur tente de les afficher en UTF-8.</p>
<p>Solutions :</p>
<p>S’il s&#8217;agit d&#8217;un texte contenu en dur dans votre page :</p>
<ul>
<li>Convertissez votre fichier en UTF-8 depuis votre éditeur de texte.</li>
<li>Vérifiez que vous envoyez bien l&#8217;entête HTTP pour déclarer les données en UTF-8.</li>
<li>Vérifiez que le jeu de caractères est bien déclaré en UTF-8 dans votre entête HTML (meta charset).</li>
</ul>
<p>Si le texte provient de la base de données :</p>
<ul>
<li>Vérifiez l&#8217;encodage de la base de données et les collations.</li>
<li>Vérifiez que vous avez bien déclaré le jeu de caractères après la connexion à la base de données (SET NAME).</li>
</ul>
<p>Si le texte provient d&#8217;une source externe (fichier, flux RSS, etc.) :</p>
<ul>
<li>Utilisez mbstring ou utf8_decode()/utf8_encode() pour convertir les données dans le bon jeu de caractères.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://nitak-studio.com/blog/2011/08/21/comment-utiliser-le-codage-utf-8-avec-php-et-mysql/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Tester la validité d&#8217;une date en JavaScript et PHP</title>
		<link>http://nitak-studio.com/blog/2011/08/21/tester-la-validite-dune-date-en-javascript-et-php/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=tester-la-validite-dune-date-en-javascript-et-php</link>
		<comments>http://nitak-studio.com/blog/2011/08/21/tester-la-validite-dune-date-en-javascript-et-php/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 12:22:58 +0000</pubDate>
		<dc:creator>JB</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP et MySQL]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[formulaire]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://nitak-studio.com/blog/?p=5</guid>
		<description><![CDATA[Généralement, on utilise une expression rationnelle pour vérifier que la syntaxe d&#8217;une date corresponde bien au résultat que l&#8217;on attend. Mais il faut aussi tester que la date soit valide : le mois ne doit pas dépasser 12, le jour ne doit pas dépasser le nombre de jours du mois, etc. Tester si l&#8217;année est ...]]></description>
			<content:encoded><![CDATA[<p>Généralement, on utilise une expression rationnelle pour vérifier que la syntaxe d&#8217;une date corresponde bien au résultat que l&#8217;on attend.</p>
<p>Mais il faut aussi tester que la date soit valide : le mois ne doit pas dépasser 12, le jour ne doit pas dépasser le nombre de jours du mois, etc.</p>
<p><span id="more-5"></span></p>
<h3>Tester si l&#8217;année est bissextile</h3>
<p>Une année bissextile contient un jour de plus qu&#8217;une année normale. Elle comporte un 29 février et possède donc 366 jours au lieu de 365.</p>
<p>Pour savoir si une année est bissextile, elle doit remplir l&#8217;un ou l&#8217;autre des critères suivants :</p>
<ul>
<li>Elle est divisible par 4, mais non divisible par 100</li>
<li>Elle est divisible par 400</li>
</ul>
<p>Il suffit donc d&#8217;écrire une fonction qui teste si l&#8217;année vérifie l&#8217;un ou l&#8217;autre de ces critères :</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> is_leap_year<span style="color: #009900;">&#40;</span>year<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #000066; font-weight: bold;">return</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span>year <span style="color: #339933;">%</span> <span style="color: #CC0000;">4</span> <span style="color: #339933;">===</span> <span style="color: #CC0000;">0</span> <span style="color: #339933;">&amp;&amp;</span> year <span style="color: #339933;">%</span> <span style="color: #CC0000;">100</span> <span style="color: #339933;">!==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> year <span style="color: #339933;">%</span> <span style="color: #CC0000;">400</span> <span style="color: #339933;">===</span> <span style="color: #CC0000;">0</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Que vous utiliserez comme ceci :</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> year <span style="color: #339933;">=</span> <span style="color: #CC0000;">1992</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>is_leap_year<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1992</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>year <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; est une année bissextile.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
 console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>year <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; n'est pas une année bissextile.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>L&#8217;équivalent en PHP coule de source :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> is_leap_year<span style="color: #009900;">&#40;</span><span style="color: #000088;">$year</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$year</span> <span style="color: #339933;">%</span> <span style="color: #cc66cc;">4</span> <span style="color: #339933;">===</span> <span style="color: #cc66cc;">0</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000088;">$year</span> <span style="color: #339933;">%</span> <span style="color: #cc66cc;">100</span> <span style="color: #339933;">!==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$year</span> <span style="color: #339933;">%</span> <span style="color: #cc66cc;">400</span> <span style="color: #339933;">===</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Tester la validité de la date</h3>
<p>Ici on ne parlera pas de tester la syntaxe de la date, mais bien si la date est valide. Pour la syntaxe, il suffit d&#8217;utiliser une expression rationnelle.</p>
<p>Pour qu&#8217;une date soit valide elle doit répondre aux critères suivants :</p>
<ul>
<li>le mois doit être une valeur comprise entre 1 et 12</li>
<li>le jour ne doit pas être plus grand que 31</li>
<li>le jour ne doit pas être plus grand que 30 pour les mois 4, 6, 9, et 11</li>
<li>si le mois est février, le jour ne doit pas être plus grand que 29, ni plus grand que 28 pour les années non bissextiles</li>
</ul>
<p>La fonction qui teste ces critères :</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> is_valid_date<span style="color: #009900;">&#40;</span>year<span style="color: #339933;">,</span> month<span style="color: #339933;">,</span> day<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
 <span style="color: #006600; font-style: italic;">// le mois doit être une valeur comprise entre 1 et 12</span>
 <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>month <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">1</span> <span style="color: #339933;">||</span> month <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">12</span><span style="color: #009900;">&#41;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #006600; font-style: italic;">// le jour ne doit pas être plus grand que 31</span>
 <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>day <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">31</span><span style="color: #009900;">&#41;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #006600; font-style: italic;">// le jour ne doit pas être plus grand que 30 pour les mois 4, 6, 9, et 11</span>
 <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>month <span style="color: #339933;">==</span> <span style="color: #CC0000;">4</span> <span style="color: #339933;">||</span> month <span style="color: #339933;">==</span> <span style="color: #CC0000;">6</span> <span style="color: #339933;">||</span> month <span style="color: #339933;">==</span> <span style="color: #CC0000;">9</span> <span style="color: #339933;">||</span> month <span style="color: #339933;">==</span> <span style="color: #CC0000;">11</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> day <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">30</span><span style="color: #009900;">&#41;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #006600; font-style: italic;">// si le mois est février...</span>
 <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>month <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// le jour ne doit pas être plus grand que 29, ni plus grand que 28 pour les années non bissextiles</span>
  <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span>day <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">29</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>is_leap_year<span style="color: #009900;">&#40;</span>year<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> day <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">28</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
   <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Que vous utiliserez comme ceci :</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> year <span style="color: #339933;">=</span> <span style="color: #CC0000;">1992</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> month <span style="color: #339933;">=</span> 02<span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> day <span style="color: #339933;">=</span> <span style="color: #CC0000;">29</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>is_valid_date<span style="color: #009900;">&#40;</span>year<span style="color: #339933;">,</span> month<span style="color: #339933;">,</span> day<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>day <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/&quot;</span> <span style="color: #339933;">+</span> month <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/&quot;</span> <span style="color: #339933;">+</span> year <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; est une date valide.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
 console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>day <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/&quot;</span> <span style="color: #339933;">+</span> month <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/&quot;</span> <span style="color: #339933;">+</span> year <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; n'est pas une date valide.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>En PHP il existe une fonction qui teste la date pour vous : checkdate()</p>
<p>Elle s&#8217;utilise simplement comme ceci :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$year</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1992</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$month</span> <span style="color: #339933;">=</span> <span style="color: #208080;">02</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$day</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">29</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">checkdate</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$month</span><span style="color: #339933;">,</span> <span style="color: #000088;">$day</span><span style="color: #339933;">,</span> <span style="color: #000088;">$year</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$day</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;/&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$month</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;/&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$year</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; est une date valide.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$day</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;/&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$month</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;/&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$year</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; n'est pas une date valide.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://nitak-studio.com/blog/2011/08/21/tester-la-validite-dune-date-en-javascript-et-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

