{"id":1189,"date":"2019-02-18T12:15:11","date_gmt":"2019-02-18T10:15:11","guid":{"rendered":"http:\/\/www.lafabriquedecode.com\/blog\/?p=1189"},"modified":"2019-02-18T12:42:33","modified_gmt":"2019-02-18T10:42:33","slug":"le-design-pattern-strategy-en-php","status":"publish","type":"post","link":"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/","title":{"rendered":"PHP &#8211; Le design pattern Strategy"},"content":{"rendered":"<p>Le design pattern <strong>Strategy<\/strong> fait partie de la famille des design patterns <strong>comportementaux<\/strong>; il facilite l&rsquo;utilisation d&rsquo;algorithmes interchangeables \u00e0 l&rsquo;ex\u00e9cution, c&rsquo;est \u00e0 dire dynamiquement. Il ob\u00e9it au bon vieux principe de la programmation orient\u00e9e objet : Encapsuler ce qui varie.<\/p>\n<p><a href=\"http:\/\/www.lafabriquedecode.com\/blog\/wp-content\/uploads\/2019\/02\/strategie.jpg\"><img loading=\"lazy\" src=\"http:\/\/www.lafabriquedecode.com\/blog\/wp-content\/uploads\/2019\/02\/strategie.jpg\" alt=\"Design pattern Strategy\" width=\"856\" height=\"561\" class=\"alignnone size-full wp-image-1191\" srcset=\"http:\/\/www.lafabriquedecode.com\/blog\/wp-content\/uploads\/2019\/02\/strategie.jpg 856w, http:\/\/www.lafabriquedecode.com\/blog\/wp-content\/uploads\/2019\/02\/strategie-300x197.jpg 300w, http:\/\/www.lafabriquedecode.com\/blog\/wp-content\/uploads\/2019\/02\/strategie-624x409.jpg 624w\" sizes=\"(max-width: 856px) 100vw, 856px\" \/><\/a><\/p>\n<h1>Les algorithmes \u00e0 encapsuler<\/h1>\n<p>Pour un comportement identique (reagir) nous avons trois impl\u00e9mentations diff\u00e9rentes. Ce sont elles que nous souhaitons isoler pour r\u00e9duire au maximum l&rsquo;impact du changement qui t\u00f4t ou tard se produira dans notre code. Ce comportement commun attend en param\u00e8tre un objet se conformant \u00e0 l&rsquo;interface <strong>StrategieInterface<\/strong> et ses impl\u00e9mentations variables consistent \u00e0 ici \u00e0 appliquer un traitement rudimentaire \u00e0 la m\u00e9thode <strong>donnerPhrase<\/strong> de cet objet en param\u00e8tre.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\ninterface StrategieInterface\r\n{\r\n    public function reagir(PersonneInterface $personne): string;\r\n}\r\n \r\nclass Enerve implements StrategieInterface\r\n{\r\n    public function reagir(PersonneInterface $personne): string\r\n    {\r\n        return strtoupper($personne-&gt;donnerPhrase().' !!!').PHP_EOL;\r\n    }\r\n}\r\n\r\nclass Geek implements StrategieInterface\r\n{\r\n    public function reagir(PersonneInterface $personne): string\r\n    {\r\n        return str_replace('o', '0', $personne-&gt;donnerPhrase()).PHP_EOL;\r\n    }\r\n}\r\n\r\nclass Jovial implements StrategieInterface\r\n{\r\n    public function reagir(PersonneInterface $personne): string\r\n    {\r\n        return ucfirst($personne-&gt;donnerPhrase()).' :)'.PHP_EOL;\r\n    }\r\n}\r\n<\/pre>\n<p>Voici notre classe <strong>Personne<\/strong> et l&rsquo;interface qu&rsquo;elle impl\u00e9mente. La seule chose qu&rsquo;elle fait est de retourner la cha\u00eene de caract\u00e8res <em>bonjour<\/em> !<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\ninterface PersonneInterface\r\n{\r\n    public function donnerPhrase(): string;\r\n}\r\n\r\nclass Personne implements PersonneInterface\r\n{\r\n    public function donnerPhrase(): string\r\n    {\r\n        return 'bonjour';\r\n    }\r\n}\r\n<\/pre>\n<h1>L&rsquo;objet Contexte<\/h1>\n<p>Voici enfin notre objet <strong>Contexte<\/strong>, partie int\u00e9grante de notre pattern. Il g\u00e8re simplement une r\u00e9f\u00e9rence \u00e0 la strat\u00e9gie, \u00e0 laquelle il transmet les requ\u00eates des clients via la d\u00e9l\u00e9gation \u00e0 la m\u00e9thode <strong>reagir<\/strong>. C&rsquo;est en quelque sorte le liant entre le code client et nos diff\u00e9rentes strat\u00e9gies concr\u00e8tes.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\nclass Contexte\r\n{\r\n    private $strategie;\r\n\r\n    public function __construct(StrategieInterface $strategie)\r\n    {\r\n        $this-&gt;strategie = $strategie;\r\n    }\r\n    \r\n    public function exprimeReaction(PersonneInterface $personne): string\r\n    {\r\n      return $this-&gt;strategie-&gt;reagir($personne);\r\n    }\r\n}\r\n<\/pre>\n<p>Pour finir, \u00e9crivons le code client qui va utiliser notre design pattern. Evidemment, nous ne nous adressons pas directement aux strat\u00e9gies mais nous passons par l&rsquo;objet <strong>Contexte<\/strong>, que nous initialiserons successivement avec des instances de chacune des strat\u00e9gies concr\u00e8tes.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n$personne = new Personne();\r\n$humeurs = [new Enerve(), new Geek(), new Jovial()];\r\n\r\nforeach ($humeurs as $humeur) {\r\n    $contexte = new Contexte($humeur);\r\n    echo $contexte-&gt;exprimeReaction($personne);\r\n}\r\n<\/pre>\n<p>A garder en t\u00eate:<\/p>\n<ul>\n<li>Un trop grand nombre de if (syndrome appel\u00e9 la for\u00eat d&rsquo;<a href=\"https:\/\/fr.wikipedia.org\/wiki\/If_commun\" rel=\"noopener\" target=\"_blank\">ifs<\/a>) est souvent le signe que <strong>Strategy<\/strong> doit \u00eatre envisag\u00e9<\/li>\n<li>Gare \u00e0 la multiplication intempestive des strat\u00e9gies concr\u00e8tes, leur nombre peut vite augmenter !<\/li>\n<li>Toutes les strat\u00e9gies concr\u00e8tes impl\u00e9mentent la m\u00eame abstraction, il peut parfois arriver qu&rsquo;elles re\u00e7oivent des informations qui ne leur seront pas utiles<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Le design pattern Strategy fait partie de la famille des design patterns comportementaux; il facilite l&rsquo;utilisation d&rsquo;algorithmes interchangeables \u00e0 l&rsquo;ex\u00e9cution, c&rsquo;est \u00e0 dire dynamiquement. Il ob\u00e9it au bon vieux principe de la programmation orient\u00e9e objet : Encapsuler ce qui varie. Les algorithmes \u00e0 encapsuler Pour un comportement identique (reagir) nous avons trois impl\u00e9mentations diff\u00e9rentes. Ce [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[24,40,88],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.6.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>PHP - Le design pattern Strategy - La Fabrique de code - Tech blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/\" \/>\n<meta property=\"og:locale\" content=\"fr_FR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PHP - Le design pattern Strategy - La Fabrique de code - Tech blog\" \/>\n<meta property=\"og:description\" content=\"Le design pattern Strategy fait partie de la famille des design patterns comportementaux; il facilite l&rsquo;utilisation d&rsquo;algorithmes interchangeables \u00e0 l&rsquo;ex\u00e9cution, c&rsquo;est \u00e0 dire dynamiquement. Il ob\u00e9it au bon vieux principe de la programmation orient\u00e9e objet : Encapsuler ce qui varie. Les algorithmes \u00e0 encapsuler Pour un comportement identique (reagir) nous avons trois impl\u00e9mentations diff\u00e9rentes. Ce [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/\" \/>\n<meta property=\"og:site_name\" content=\"La Fabrique de code - Tech blog\" \/>\n<meta property=\"article:published_time\" content=\"2019-02-18T10:15:11+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-02-18T10:42:33+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.lafabriquedecode.com\/blog\/wp-content\/uploads\/2019\/02\/strategie.jpg\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary\" \/>\n<meta name=\"twitter:creator\" content=\"@LaFabrique2Code\" \/>\n<meta name=\"twitter:site\" content=\"@LaFabrique2Code\" \/>\n<meta name=\"twitter:label1\" content=\"\u00c9crit par\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Dur\u00e9e de lecture estim\u00e9e\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/\",\"url\":\"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/\",\"name\":\"PHP - Le design pattern Strategy - La Fabrique de code - Tech blog\",\"isPartOf\":{\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/#website\"},\"datePublished\":\"2019-02-18T10:15:11+00:00\",\"dateModified\":\"2019-02-18T10:42:33+00:00\",\"author\":{\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/#\/schema\/person\/83863c048b82fd9ccf6407bddd241162\"},\"breadcrumb\":{\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/#breadcrumb\"},\"inLanguage\":\"fr-FR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Accueil\",\"item\":\"http:\/\/www.lafabriquedecode.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PHP &#8211; Le design pattern Strategy\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/#website\",\"url\":\"http:\/\/www.lafabriquedecode.com\/blog\/\",\"name\":\"La Fabrique de code - Tech blog\",\"description\":\"PHP objet, MySQL, Design Patterns, OOP...et plus !\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/www.lafabriquedecode.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"fr-FR\"},{\"@type\":\"Person\",\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/#\/schema\/person\/83863c048b82fd9ccf6407bddd241162\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-FR\",\"@id\":\"http:\/\/www.lafabriquedecode.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"http:\/\/0.gravatar.com\/avatar\/fc2e1de7c8a1871b50ff9c6a6f8682a2?s=96&d=retro&r=g\",\"contentUrl\":\"http:\/\/0.gravatar.com\/avatar\/fc2e1de7c8a1871b50ff9c6a6f8682a2?s=96&d=retro&r=g\",\"caption\":\"admin\"},\"url\":\"http:\/\/www.lafabriquedecode.com\/blog\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"PHP - Le design pattern Strategy - La Fabrique de code - Tech blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/","og_locale":"fr_FR","og_type":"article","og_title":"PHP - Le design pattern Strategy - La Fabrique de code - Tech blog","og_description":"Le design pattern Strategy fait partie de la famille des design patterns comportementaux; il facilite l&rsquo;utilisation d&rsquo;algorithmes interchangeables \u00e0 l&rsquo;ex\u00e9cution, c&rsquo;est \u00e0 dire dynamiquement. Il ob\u00e9it au bon vieux principe de la programmation orient\u00e9e objet : Encapsuler ce qui varie. Les algorithmes \u00e0 encapsuler Pour un comportement identique (reagir) nous avons trois impl\u00e9mentations diff\u00e9rentes. Ce [&hellip;]","og_url":"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/","og_site_name":"La Fabrique de code - Tech blog","article_published_time":"2019-02-18T10:15:11+00:00","article_modified_time":"2019-02-18T10:42:33+00:00","og_image":[{"url":"http:\/\/www.lafabriquedecode.com\/blog\/wp-content\/uploads\/2019\/02\/strategie.jpg"}],"author":"admin","twitter_card":"summary","twitter_creator":"@LaFabrique2Code","twitter_site":"@LaFabrique2Code","twitter_misc":{"\u00c9crit par":"admin","Dur\u00e9e de lecture estim\u00e9e":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/","url":"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/","name":"PHP - Le design pattern Strategy - La Fabrique de code - Tech blog","isPartOf":{"@id":"http:\/\/www.lafabriquedecode.com\/blog\/#website"},"datePublished":"2019-02-18T10:15:11+00:00","dateModified":"2019-02-18T10:42:33+00:00","author":{"@id":"http:\/\/www.lafabriquedecode.com\/blog\/#\/schema\/person\/83863c048b82fd9ccf6407bddd241162"},"breadcrumb":{"@id":"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/#breadcrumb"},"inLanguage":"fr-FR","potentialAction":[{"@type":"ReadAction","target":["http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/"]}]},{"@type":"BreadcrumbList","@id":"http:\/\/www.lafabriquedecode.com\/blog\/2019\/02\/le-design-pattern-strategy-en-php\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Accueil","item":"http:\/\/www.lafabriquedecode.com\/blog\/"},{"@type":"ListItem","position":2,"name":"PHP &#8211; Le design pattern Strategy"}]},{"@type":"WebSite","@id":"http:\/\/www.lafabriquedecode.com\/blog\/#website","url":"http:\/\/www.lafabriquedecode.com\/blog\/","name":"La Fabrique de code - Tech blog","description":"PHP objet, MySQL, Design Patterns, OOP...et plus !","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/www.lafabriquedecode.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"fr-FR"},{"@type":"Person","@id":"http:\/\/www.lafabriquedecode.com\/blog\/#\/schema\/person\/83863c048b82fd9ccf6407bddd241162","name":"admin","image":{"@type":"ImageObject","inLanguage":"fr-FR","@id":"http:\/\/www.lafabriquedecode.com\/blog\/#\/schema\/person\/image\/","url":"http:\/\/0.gravatar.com\/avatar\/fc2e1de7c8a1871b50ff9c6a6f8682a2?s=96&d=retro&r=g","contentUrl":"http:\/\/0.gravatar.com\/avatar\/fc2e1de7c8a1871b50ff9c6a6f8682a2?s=96&d=retro&r=g","caption":"admin"},"url":"http:\/\/www.lafabriquedecode.com\/blog\/author\/admin\/"}]}},"_links":{"self":[{"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/posts\/1189"}],"collection":[{"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/comments?post=1189"}],"version-history":[{"count":16,"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/posts\/1189\/revisions"}],"predecessor-version":[{"id":1206,"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/posts\/1189\/revisions\/1206"}],"wp:attachment":[{"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/media?parent=1189"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/categories?post=1189"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.lafabriquedecode.com\/blog\/wp-json\/wp\/v2\/tags?post=1189"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}