<?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>Amicalement Web - Astuces et Bons plans dans le développement web &#187; orm</title>
	<atom:link href="http://www.amicalement-web.net/tag/orm/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.amicalement-web.net</link>
	<description>Astuces et bons plans d&#039;un web developpeur</description>
	<lastBuildDate>Wed, 04 Jan 2012 14:54:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Doctrine2 : au revoir ActiveRecord, bonjour DataMapper !</title>
		<link>http://www.amicalement-web.net/doctrine2-au-revoir-activerecord-bonjour-datamapper/2011/01/03/</link>
		<comments>http://www.amicalement-web.net/doctrine2-au-revoir-activerecord-bonjour-datamapper/2011/01/03/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 08:55:29 +0000</pubDate>
		<dc:creator>Vince</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[active record]]></category>
		<category><![CDATA[datamapper]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[orm]]></category>

		<guid isPermaLink="false">http://www.amicalement-web.net/?p=1413</guid>
		<description><![CDATA[Aujourd&#8217;hui nous allons parler d&#8217;un ORM pour PHP que vous connaissez sûrement : Doctrine (si vous ne le connaissez pas je ne peux rien pour vous, ou alors juste vous donner l&#8217;adresse du site). Cela fait maintenant quelques années que Doctrine 1 a vu le jour et a été utilisé dans nombre de projets symfony, [...]]]></description>
			<content:encoded><![CDATA[<p><a  href="http://www.amicalement-web.net/doctrine2-au-revoir-activerecord-bonjour-datamapper/2011/01/03/"><img src="http://www.amicalement-web.net/wp-content/uploads/doctrine1.png" alt="" title="doctrine" width="614" height="100" class="alignnone size-full wp-image-1655" /></a><br />
Aujourd&#8217;hui nous allons parler d&#8217;un <a  href="http://fr.wikipedia.org/wiki/Mapping_objet-relationnel">ORM</a> pour PHP que vous connaissez sûrement : Doctrine (si vous ne le connaissez pas je ne peux rien pour vous, ou alors juste vous donner <a  href="http://www.doctrine-project.org">l&#8217;adresse du site</a>). Cela fait maintenant quelques années que Doctrine 1 a vu le jour et a été utilisé dans nombre de projets symfony, mais il est temps pour lui de prendre sa retraite, et par l&#8217;occasion de dire au revoir (ou presque) au design pattern <a  href="http://www.martinfowler.com/eaaCatalog/activeRecord.html">Active Record</a> qui va avec. D&#8217;ailleurs ça tombe bien, Doctrine 2 vient de sortir sa première version stable !<br />
<span id="more-1413"></span></p>
<h3>Modèle et persistance</h3>
<p>La première chose que l&#8217;on m&#8217;a apprise lorsqu&#8217;on m&#8217;a parlé de MVC, c&#8217;était que le M (pour model) devait contenir la <strong>logique &laquo;&nbsp;métier&nbsp;&raquo;</strong> de notre application. Quand on parle de métier, c&#8217;est bien ce qui est spécifique à l&#8217;application développée. La partie Modèle d&#8217;une calculatrice doit savoir calculer (Lapalisse si tu m&#8217;entends, elle est pour toi celle là), la partie Modèle d&#8217;une gestion de facturation doit savoir gérer les relances, les impayés, les factures &#8230; Bon bah très bien tout ça.</p>
<p>Et là c&#8217;est le drame, vous vous mettez à utiliser symfony et un des deux principaux ORM du monde PHP : <strong>Propel ou Doctrine</strong>. Tout d&#8217;abord vous trouvez ça chouette, vous pouvez faire un <strong>->save() ou un ->delete()</strong> directement sur votre objet, la classe. Mais qu&#8217;est-ce que ça veut dire ça ? Ca veut dire que votre objet connait la façon dont il doit persister. Il est fortement couplé à la façon dont vous voulez l&#8217;enregistrer, dans notre cas dans une base de données.</p>
<p>C&#8217;est assez facile à voir, regardez le graphe d&#8217;héritage de votre objet, pour Doctrine tous les objets de votre modèle héritent de la classe <code>Doctrine_Record</code>. Et si, par le plus grand des hasards, vous voulez réutiliser votre logique métier dans une autre application PHP qui n&#8217;a rien à voir avec celle que vous développez avec symfony/Doctrine ? Vous êtes bons pour de jolis copier/coller.</p>
<h3>DataMapper à la rescousse</h3>
<p>L&#8217;idéal pour réaliser des M qui ne font que du M, c&#8217;est de n&#8217;avoir que des <strong>PPO (Plain PHP Object)</strong>, c&#8217;est à dire des objets PHP standards (qui n&#8217;héritent pas d&#8217;une classe comme <code>Doctrine_Record</code> par exemple). Ces PPO doivent réaliser la logique métier de notre application (le M), et une autre partie de l&#8217;application doit pouvoir prendre ce PPO et le faire persister quelque part (système de fichier, base de données, &#8230;). C&#8217;est là qu&#8217;intervient le design pattern <a  href="http://martinfowler.com/eaaCatalog/dataMapper.html"><strong>DataMapper</strong></a>. Il va permettre de faire le lien entre l&#8217;objet (l&#8217;Entity dans le jargon Doctrine2) et la façon dont il devra persister. Dans Doctrine2, c&#8217;est l&#8217;<a  href="http://www.doctrine-project.org/api/orm/2.0/doctrine/orm/entitymanager.html">Entity Manager</a> qui va réaliser le rôle de DataMapper avec sa méthode flush() qui sauvegarde les changements dans la base de données.</p>
<h3>Unit of Work, le copain du DataMapper</h3>
<p>La méthode ->flush() de l&#8217;EntityManager va permettre d&#8217;enregistrer les changements effectués sur les PPO dans la base de données. Ces changements auront été notifiés au préalable à l&#8217;Entity Manager par la méthode persist(). Cette méthode permet de dire à l&#8217;Entity Manager que l&#8217;on veut faire persister notre PPO passé en paramètre de la méthode. Ça se résume comme ça :</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> User<span style="color: #339933;">;</span>
<span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Mr.Right'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$em</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">persist</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$em</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Ici on informe l&#8217;Entity Manager (em), que l&#8217;on voudra faire persister les changements apportés à l&#8217;objet user via la méthode <code>$em->persist($user)</code>. Les changements ne seront effectués dans la base de données qu&#8217;une fois la méthode ->flush() invoquée. Si nous avions fait plusieurs ->persist() différents avant de faire notre ->flush(), rien n&#8217;aurait encore été écrit dans la base. Mais alors, comment Doctrine fait pour garder trace de ces changements jusqu&#8217;au flush ? Il utilise le design pattern <a  href="http://martinfowler.com/eaaCatalog/unitOfWork.html"><strong>Unit of Work</strong></a>. Ce design pattern permet de garder trace de toutes les modifications apportées entre 2 flush(). Il met en place une sorte de <strong>transaction, mais au niveau des objets</strong>. C&#8217;est en partie son utilisation qui permet d&#8217;avoir un beau Data Mapper comme l&#8217;EM.</p>
<h3>Conclusion</h3>
<p>L&#8217;utilisation d&#8217;un DataMapper n&#8217;est pas vraiment nouveau dans le monde de la programmation : <a  href="http://www.hibernate.org/">Hibernate</a> l&#8217;implémente déjà pour Java et <a  href="http://www.sqlalchemy.org/">SQLAlchemy</a> pour Python. En revanche, c&#8217;est une <strong>petite révolution dans le monde PHP</strong>. Si des fois vous préférez garder votre bon vieux <strong>Active Record</strong>, il existe aussi des solution en PHP : vous pouvez utiliser l&#8217;<a  href="http://www.propelorm.org/">ORM Propel</a> qui est toujours activement maintenu par François Zaninotto ou utiliser des implémentations du pattern Active Record réalisées avec Doctrine2 comme <a  href="https://github.com/pablodip/doctrator">Doctractor</a> ou <a  href="http://www.doctrine-project.org/blog/your-own-orm-doctrine2">ActiveEntity</a> codé par l&#8217;équipe de Doctrine2. C&#8217;est deux derniers exemples montrent bien toute la flexibilité et la puissance de cette nouvelle version de Doctrine !</p>
]]></content:encoded>
			<wfw:commentRss>http://www.amicalement-web.net/doctrine2-au-revoir-activerecord-bonjour-datamapper/2011/01/03/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Développement Web: les bons plans de la semaine #22</title>
		<link>http://www.amicalement-web.net/developpement-web-les-bons-plans-de-la-semaine-22/2009/11/09/</link>
		<comments>http://www.amicalement-web.net/developpement-web-les-bons-plans-de-la-semaine-22/2009/11/09/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 10:00:47 +0000</pubDate>
		<dc:creator>Tim</dc:creator>
				<category><![CDATA[Bons plans]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[propel]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://www.amicalement-web.net/?p=950</guid>
		<description><![CDATA[De la chair fraîche pour cette semaine! Vous devriez avoir un autre billet que celui-ci cette semaine encore si vous êtes sage. On m&#8217;a soufflé que ca pourrait parler de WordPress! Un sujet un peu oublié depuis la V2 mais qui m&#8217;intéresse toujours autant. Wait and see mais en attendant voici la sélection de la [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.amicalement-web.net/wp-content/uploads/enveloppe.png" alt="enveloppe" title="enveloppe" width="614" height="100" class="alignnone size-full wp-image-956" /> De la chair fraîche pour cette semaine! Vous devriez avoir un autre billet que celui-ci cette semaine encore si vous êtes sage. On m&#8217;a soufflé que ca pourrait parler de WordPress! Un sujet un peu oublié depuis la V2 mais qui m&#8217;intéresse toujours autant.</p>
<p>Wait and see mais en attendant voici la sélection de la semaine.<br />
<span id="more-950"></span></p>
<ul>
<li><a  href="http://propel.posterous.com/propel-140-stable-is-there">Propel 1.4 stable</a><br />
C&#8217;est un peu l&#8217;annonce de la semaine. Propel 1.4 stable est sortie! Pas mal de nouveautés dont certaines reprises des bonnes idées de Doctrine, mais également quelques exclus. Peut-être un futur billet plus complet à ce sujet ;)</li>
<li><a  href="http://wordpress.digitalnature.ro/mystique/">Un joli thème wordpress</a><br />
Une fois n&#8217;est pas coutume, croisé au détour d&#8217;un clic, assez sobre mais bourré de petits détails.</li>
<li><a  href="http://demo.kreativethemes.com/furvious/?kreativestyle=02">Un autre joli thème wordpress</a><br />
Comme quoi ya des semaines comme ça. Celui-ci est plus poussé graphiquement mais a un vrai potentiel je pense</li>
<li><a  href="http://davidwalsh.name/text-selection-ajax">Event jquery sur la sélection de texte</a><br />
Fonctionnalité qui pourrait ouvrir la porte à quelques nouvelles possibilités sympa</li>
<li><a  href="http://validatious.org/">Un nouveau script de validation de formulaire</a><br />
Oui encore un. Ca faisait longtemps. Mais celui-ci est vraiment bien fini et permet de définir ses validations avec très peu de ligne js, tout étant calibré depuis le code html</li>
<li><a  href="http://papermashup.com/using-memcache-with-php/">Memcache et le PHP</a><br />
Une petite explication sur Memcache et ses bienfaits pour le PHP</li>
<li><a  href="http://webdeveloperplus.com/jquery/quick-easy-way-to-implement-drag-n-share-with-jquery/">Drag and share avec jQuery</a><br />
Une façon originale de penser le drag and drop et le partage sur les medias sociaux.</li>
<li><a  href="http://www.alsacreations.com/actu/lire/899-optimiser-les-javascripts-avec-google-closure-tools-et-closure-compiler.html">Un compilateur javascript par Google</a><br />
C&#8217;est le lien qui a fait le tour du web, cette semaine. Le voilà décrit par dew, même s&#8217;il s&#8217;avère très compliqué d&#8217;être utilisé avec jquery, ca reste un outil assez novateur.</li>
<li><a  href="http://www.phpactiverecord.org/">Un nouvel ORM PHP</a><br />
Basé sur l&#8217;ORM de Ruby, voici un ORM dont on pourrait bien entendre parler prochainement.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.amicalement-web.net/developpement-web-les-bons-plans-de-la-semaine-22/2009/11/09/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Doctrine: quelques petits secrets</title>
		<link>http://www.amicalement-web.net/doctrine-quelques-petits-secrets/2009/08/26/</link>
		<comments>http://www.amicalement-web.net/doctrine-quelques-petits-secrets/2009/08/26/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 09:00:38 +0000</pubDate>
		<dc:creator>Tim</dc:creator>
				<category><![CDATA[Astuces]]></category>
		<category><![CDATA[astuce]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://www.amicalement-web.net/?p=582</guid>
		<description><![CDATA[Oui, je commence à parler de Doctrine de plus en plus vu que je commence à l&#8217;utiliser à grande échelle au boulot. Et il y a un détail où j&#8217;ai encore du mal, c&#8217;est l&#8217;opacité de cet ORM comparé à son prédécesseur dans Symfony, Propel. On se rappelle tous (enfin je parle au passé, mais [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.amicalement-web.net/wp-content/uploads/doctrine-secret.png" alt="doctrine-secret" title="doctrine-secret" width="614" height="100" class="alignnone size-full wp-image-640" /> Oui, je <a  href="/doctrine-et-son-behavior-geographical/2009/08/05/">commence à parler de Doctrine</a> de plus en plus vu que je commence à l&#8217;utiliser à grande échelle au boulot. Et il y a un détail où j&#8217;ai encore du mal, c&#8217;est l&#8217;opacité de cet ORM comparé à son prédécesseur dans Symfony, Propel.</p>
<p>On se rappelle tous (enfin je parle au passé, mais Propel n&#8217;est pas mort hein :p) qu&#8217;on avait tout à disposition dans le BasePeer de notre modèle, les accesseurs, les modificateurs et quasi toutes les méthodes dont on pouvait avoir besoin. Avec Doctrine, la donne a changé, tant cet ORM est codé différemment.</p>
<p>On se retrouve du coup un peu perdu parfois, sans trop savoir ce qu&#8217;on peut utiliser. Et là, il faut bien sûr jeter un œil à l&#8217;<a href="http://www.doctrine-project.org/documentation/api/1_1 ">API Doctrine</a>. Mais on le sait tous, on a pas toujours le temps! Du coup, au travers de mes recherches, j&#8217;ai trouvé quelques petites méthodes que j&#8217;utilise régulièrement et dont je vais vous parler.<br />
<span id="more-582"></span></p>
<h3>Le modèle d&#8217;exemple</h3>
<p>Afin d&#8217;illustrer au mieux les différentes fonctions, je vais prendre en exemple un modèle basique, une liste de lien:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">MyLink:
  columns:
    name: { type: string(100), notnull: true }
    link: { type: string(255), notnull: true }
    description: { type: string(4000) }</pre></div></div>

<h3>Un save qui retourne un booléen</h3>
<p>Parfois, lors de petites modifications, on a pas toujours le courage de faire un try/catch sur notre transaction. TrySave répond à cette problématique, en incluant directement le try catch sur le save et en retournant un booléen, true si l&#8217;enregistrement a bien été commité, false si une exception a été levée. Bien pratique!</p>
<ul>
<li> <a  href="http://www.doctrine-project.org/Doctrine_Record/1_1#method_trysave">Documentation trySave</a></li>
<li> Exemple:

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> saveMyLink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$link</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyLink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">name</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Amicalement-web'</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://www.amicalement-web.net'</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">return</span> <span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">trySave</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Retournera true si la sauvegarde a été effectuée, false sinon</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

</li>
</ul>
<h3>Le nom de la clé primaire</h3>
<p>Oui des fois, quand on veut généraliser une méthode, on a besoin du nom de la clé primaire de notre model. (Dans le cas d&#8217;un unset en vue d&#8217;un embedForm par exemple).</p>
<ul>
<li><a  href="http://www.doctrine-project.org/Doctrine_Table/1_1#method_getidentifier">Documentation getIdentifier</a></li>
<li> Exemple:

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$link</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyLink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getTable</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getIdentifier</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

</li>
</ul>
<h3>Exporter votre modèle en différents formats</h3>
<p>Que se soit pour générer des XML destinés à une application tiers, ou du json pour votre module javascript, on a souvent besoin de nos modèles dans un format d&#8217;échange. Et bien Doctrine intègre cette fonctionnalité de base, en permettant des export en tableau php, xml, yml et json.</p>
<ul>
<li><a  href="http://www.doctrine-project.org/Doctrine_Record/1_1#method_exportto">Documentation exportTo</a></li>
<li>Exemple

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$link</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyLink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">name</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Symfony Project'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">link</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://www.symfony-project.org'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">exportTo</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'xml'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Attention par défaut exporte aussi les relations de l'objets. Il faut mettre à false, le 2e argument si on veut conserver seulement notre objet en question</span></pre></div></div>

</li>
<li>
Rendu:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Symfony Project<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://www.symfony-project.org<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;description<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/description<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</li>
</ul>
<h3>Importer votre modèle en différents formats</h3>
<p>Et oui parce que Doctrine fait les choses biens, la réciproque existe aussi et est toute aussi utile. Vous pouvez ainsi hydrater  un objet à partir d&#8217;un xml, json, ou yml grâce à la méthode importFrom</p>
<ul>
<li><a  href="http://www.doctrine-project.org/Doctrine_Record/1_1#method_importfrom">Documentation importFrom</a></li>
<li>Exemple:

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$json</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'{&quot;id&quot;:&quot;5&quot;,&quot;name&quot;:&quot;Doctrine Project&quot;,&quot;url&quot;:&quot;http:\/\/www.doctrine-project.org&quot;,&quot;description&quot;:&quot;Orm PHP&quot;}'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyLink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">importFrom</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'json'</span><span style="color: #339933;">,</span><span style="color: #000088;">$json</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$link</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">name</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Affiche &quot;Doctrine Project&quot;</span></pre></div></div>

</li>
</ul>
<p>Pour ce qui est d&#8217;hydrater à partir d&#8217;un tableau php, il y a 2 méthodes pour ça: fromArray et hydrate. Leurs différences, c&#8217;est la façon de faire. La première utilise les modificateurs de notre modèle (permettant ainsi de passer par des modifications qu&#8217;on aurait pu apporter à ces méthodes &laquo;&nbsp;set&nbsp;&raquo;) alors que la seconde remplie directement les attributs de notre modèle.</p>
<ul>
<li><a  href="http://www.doctrine-project.org/Doctrine_Record/1_1#method_fromarray">Documentation fromArray</a></li>
<li><a  href="http://www.doctrine-project.org/Doctrine_Record/1_1#method_hydrate">Documentation hydrate</a></li>
<li>
Exemple:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// On surcharge le modificateur de la propriété $url pour rajouter 'http://' devant</span>
<span style="color: #000000; font-weight: bold;">class</span> MyLink <span style="color: #000000; font-weight: bold;">extends</span> BaseMyLink
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setUrl<span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    parent<span style="color: #339933;">::</span>_set<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'url'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'http://'</span><span style="color: #339933;">.</span><span style="color: #000088;">$url</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>

<p>Puis maintenant nos 2 appels:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$data</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'name'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Amicalement Web'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'url'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'www.amicalement-web.net'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link1</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyLink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">fromArray</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'link1='</span><span style="color: #339933;">.</span><span style="color: #000088;">$link1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Affiche http://www.amicalement-web.net</span>
&nbsp;
<span style="color: #000088;">$link2</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyLink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$link2</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">hydrate</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'link2='</span><span style="color: #339933;">.</span><span style="color: #000088;">$link2</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Affiche www.amicalement-web.net</span></pre></div></div>

</li>
</ul>
<h3>Post/Pre methodes</h3>
<p>Comme je l&#8217;avais utilisé dans l&#8217;exemple du behavior Geographical, Doctrine met à disposition toute une série de méthodes en post et pré traitement de nombreuses fonctionnalités comme</p>
<ul>
<li>Sérialisation</li>
<li>Désérialisation</li>
<li>Sauvegarde</li>
<li>Suppression</li>
<li>Mise à jour</li>
<li>Insertion</li>
<li>Validation</li>
<li>Hydratation</li>
</ul>
<p><a  href="http://www.doctrine-project.org/Doctrine_Record/1_2#method_postdelete">Leur documentation</a> à la suite les unes des autre.</p>
<h3>Libérer de la mémoire</h3>
<p>La performance, sans être un axe principal a mon goût, doit rester dans la tête de chacun. Pour ça, Doctrine propose une méthode pour effacer un objet ainsi que toutes ses références de la mémoire de l&#8217;ORM. A utiliser principalement dans des boucles quand on veut juste faire un traitement sur un ensemble d&#8217;objets dont on ne voudra pas se resservir ensuite.</p>
<ul>
<li><a  href="http://www.doctrine-project.org/Doctrine_Record/1_1#method_free">Documentation free</a></li>
<li>Exemple:

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Exemple tiré de la documentation doctrine</span>
<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">1000</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$object</span> <span style="color: #339933;">=</span> createBigObject<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$object</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$object</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">free</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// true pour libérer même les relations</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

</li>
</ul>
<h3>Hydrater plus efficacement</h3>
<p>Et oui, on le crie pas sur tous les toits, mais on est pas obligé de récupérer des objets complets quand on fait une requête avec doctrine même si c&#8217;est le comportement par défaut.<br />
Quand on veut simplement faire de l&#8217;affichage, parfois seules les données nous intéresse et donc dans un gain de mémoire, on peut changer le mode d&#8217;hydratation:</p>
<ul>
<li>Doctrine::HYDRATE_RECORD</li>
<li>Doctrine::HYDRATE_ARRAY</li>
<li>Doctrine::HYDRATE_NONE</li>
<li>Exemple:

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$q</span> <span style="color: #339933;">=</span> Doctrine_Query<span style="color: #339933;">::</span><span style="color: #004000;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">from</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'MyLink'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Comportement par défaut, retourne un tableau d'objet</span>
<span style="color: #000088;">$results</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$q</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">HYDRATE_RECORD</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Retourne un tableau associatif où les clés sont les noms des champs</span>
<span style="color: #000088;">$results</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$q</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">HYDRATE_ARRAY</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Retourne un simple tableau où les champs sont dans l'ordre qu'ils ont été appelés</span>
<span style="color: #000088;">$results</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$q</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">HYDRATE_NONE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

</li>
</ul>
<p>Cela reste le fruit de mes tests et études, si vous avez des remarques ou des corrections n&#8217;hésitez pas!</p>
<p>Et vous, vous avez quelque chose à partager sur les méandres de Doctrine?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.amicalement-web.net/doctrine-quelques-petits-secrets/2009/08/26/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->
