<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kevin Wenger on Medium]]></title>
        <description><![CDATA[Stories by Kevin Wenger on Medium]]></description>
        <link>https://medium.com/@wengerk?source=rss-43dda52695e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AYspR4B7ytow39TeGZLOaw.png</url>
            <title>Stories by Kevin Wenger on Medium</title>
            <link>https://medium.com/@wengerk?source=rss-43dda52695e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:24:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wengerk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Symfony Request: stop guessing where your ingredients come from ‍]]></title>
            <link>https://wengerk.medium.com/symfony-request-stop-guessing-where-your-ingredients-come-from-5cea7e925dc2?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cea7e925dc2</guid>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 06:01:02 GMT</pubDate>
            <atom:updated>2026-10-21T06:01:02.468Z</atom:updated>
            <content:encoded><![CDATA[<p>The other day I was reviewing a pull request and noticed this one-line diff:</p><pre>- $search = (string) $request-&gt;query-&gt;get(&#39;q&#39;, &#39;&#39;);<br>+ $search = $request-&gt;query-&gt;getString(&#39;q&#39;, &#39;&#39;);</pre><p>It looks like nothing. But it reflects a broader change in how Symfony wants us to read HTTP requests: <strong>say where the data comes from, say what type you expect and let the framework complain for you.</strong></p><p>Let’s step into a restaurant kitchen: your controller is the cook, and the request is everything that lands on the counter 🍳</p><p>Not a Medium member yet? <a href="https://wengerk.medium.com/5cea7e925dc2?source=friends_link&amp;sk=49f759e3cbce23ea2f2ba4e7fa9bfd9d">Click here to access this article for free!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtqk6gKtoSVqZyyCCRSbAA.jpeg" /></figure><h3>🥫 Pick your shelf</h3><p>$request-&gt;get(&#39;key&#39;) looks in three places, in this order: the route attributes, the query string, then the POST body. It returns the first match.</p><p>Picture a kitchen assistant who, when you ask for “salt”, grabs the first thing labelled salt from the order ticket, then the fridge, then the delivery crates. You get <em>some</em> salt, but you have no idea where it came from.</p><p>It’s handy, but it’s ambiguous. Your form posts an amount field, someone adds ?amount=1 to the URL, and the query string silently wins over the body. Reading the code, nobody can tell which one you actually meant.</p><p>In Symfony 7.4, Request::get() is deprecated. It&#39;s removed in Symfony 8.0.</p><p><strong>Before</strong></p><pre>public function update(Request $request): Response<br>{<br>    // Route? Query string? Body? Nobody knows 🤷<br>    $id = $request-&gt;get(&#39;id&#39;);<br>    $amount = $request-&gt;get(&#39;amount&#39;);<br>}</pre><p><strong>After</strong></p><pre>public function update(Request $request, string $id): Response<br>{<br>    // Route placeholders: just use a controller argument ($id)<br>    // or $request-&gt;attributes-&gt;get(&#39;id&#39;) if you really need to<br>    // Query string (?filter=…).<br>    $filter = $request-&gt;query-&gt;getString(&#39;filter&#39;);<br><br>    // POST body.<br>    $amount = $request-&gt;request-&gt;getInt(&#39;amount&#39;);<br>}</pre><p>One labelled shelf per source. Anyone reading the recipe knows exactly where each ingredient comes from.</p><p>Check your profiler’s deprecation tab: you’ll probably find more get() calls than you&#39;d expect.</p><h3>🍌 Stop casting, start typed</h3><p>Now that we take ingredients from the right shelf, let’s look at <em>what</em> we’re actually taking.</p><p>$request-&gt;query and $request-&gt;request are InputBags. Since Symfony 6, InputBag::get() only returns a scalar or null: string|int|float|bool|null. If someone sends ?q[]=oops, you get a 400 Bad Request rather than an array showing up somewhere it shouldn&#39;t.</p><p>That narrow return type is great, but it’s still up to four different types. So we cast, and casting accepts anything without complaining:</p><p><strong>Before</strong></p><pre>$search = (string) $request-&gt;query-&gt;get(&#39;q&#39;, &#39;&#39;);<br>$page = (int) $request-&gt;query-&gt;get(&#39;page&#39;, 1);     // &quot;?page=banana&quot; → 0 🍌<br>$active = (bool) $request-&gt;query-&gt;get(&#39;active&#39;);   // &quot;?active=false&quot; → true 🙃</pre><p>Casting is like a cook who ordered eggs, receives a banana, and makes the omelette anyway. &quot;false&quot; becomes true, &quot;banana&quot; becomes 0 and the dish goes out as if nothing happened.</p><p><strong>After</strong></p><pre>$search = $request-&gt;query-&gt;getString(&#39;q&#39;);        // always a string<br>$page = $request-&gt;query-&gt;getInt(&#39;page&#39;, 1);       // &quot;?page=banana&quot; → 400<br>$active = $request-&gt;query-&gt;getBoolean(&#39;active&#39;);  // &quot;false&quot; → false, &quot;maybe&quot; → 400<br><br>// Need a list? Say so explicitly<br>$ids = $request-&gt;query-&gt;all(&#39;ids&#39;);               // &quot;?ids=foo&quot; → 400<br>// And for a fixed set of values, use a backed enum<br>$status = $request-&gt;query-&gt;getEnum(&#39;status&#39;, Status::class, Status::Draft);</pre><p>Typed getters are the quality check at the kitchen door. You say “I ordered eggs”, and if bananas show up, the delivery is sent back. In Symfony 7, invalid values in an InputBag end up as a clean 400 Bad Request, and you don&#39;t have to write any validation code for it.</p><h3>📦 The back-door deliveries</h3><p>One delivery was always left in its box. PHP only parsed form bodies (application/x-www-form-urlencoded and multipart/form-data) for POST, the main entrance. Send the same form with PUT, through the back door, and $request-&gt;request came back empty. The crate was there, but nobody opened it.</p><p>Symfony 7.4 on PHP 8.4 uses the new request_parse_body() function, so non-POST bodies get unpacked too.</p><p><strong>Before</strong></p><pre>#[Route(&#39;/api/articles/{id}&#39;, methods: [&#39;PUT&#39;])]<br>public function update(Request $request): Response<br>{<br>    // $request-&gt;request is empty for PUT… so we open the crate by hand.<br>    parse_str($request-&gt;getContent(), $data);<br>    $title = $data[&#39;title&#39;] ?? &#39;&#39;;<br><br>    // File uploads? Fake a POST with _method=PUT 🥲<br>}</pre><p><strong>After</strong> (Symfony 7.4 + PHP 8.4)</p><pre>#[Route(&#39;/api/articles/{id}&#39;, methods: [&#39;PUT&#39;])]<br>public function update(Request $request): Response<br>{<br>    // Works exactly like POST now.<br>    $title = $request-&gt;request-&gt;getString(&#39;title&#39;);<br>    $cover = $request-&gt;files-&gt;get(&#39;cover&#39;);<br>}</pre><p>This is also what makes form-encoded QUERY requests work, as I mentioned in the previous article.</p><h3>🍽️ Wrapping up</h3><p>None of these changes will change your life on its own. Together they make your controllers <strong>more explicit and harder to trick</strong>:</p><ul><li>one shelf per source: attributes, query, request instead of get(),</li><li>a quality check instead of casts: getString(), getInt(), getBoolean(), getEnum(), all(),</li><li>every delivery unpacked: real body parsing for PUT, PATCH and DELETE.</li></ul><p>What you can do now: search your codebase for $request-&gt;get() or $request-&gt; and fix them before Symfony 8.</p><p>And if you want to go one step further and stop touching the Request object altogether, have a look at #[MapQueryParameter], #[MapQueryString] and #[MapRequestPayload].</p><p>I wrote about them in <a href="https://wengerk.medium.com/symfony-controller-request-data-mapping-a-modern-approach-d42bf77a7645">Symfony Controller Request Data Mapping: A Modern Approach</a>. It&#39;s like having your ingredients prepped and portioned before you even start cooking.</p><p>❤️ Love on your keyboards &amp; Happy coding.</p><h3>Sources</h3><p>The <a href="https://symfony.com/doc/current/components/http_foundation.html">official Symfony HTTPFoundation documentation</a>.</p><p><strong>Javier Eguiluz</strong> (2025) New in Symfony 7.4: Request Class Improvements.<br><a href="https://symfony.com/blog/new-in-symfony-7-4-request-class-improvements">https://symfony.com/blog/new-in-symfony-7-4-request-class-improvements</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cea7e925dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP QUERY in Symfony: when your GET doesn’t fit on a postcard ]]></title>
            <link>https://wengerk.medium.com/http-query-in-symfony-when-your-get-doesnt-fit-on-a-postcard-a3150623a2ba?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3150623a2ba</guid>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 05:01:02 GMT</pubDate>
            <atom:updated>2026-09-29T06:09:29.289Z</atom:updated>
            <content:encoded><![CDATA[<p>Every developer has had to choose between “correct” and “working” at some point.</p><p><em>Not a Medium member yet? </em><a href="https://wengerk.medium.com/a3150623a2ba?source=friends_link&amp;sk=95dc5861710f34f04ba313676271958a"><em>Click here to access this article for free</em></a><em>!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iw7p2w8evhbzct4zbc3pLg.jpeg" /></figure><p>You’re building a search endpoint. It only reads data, so it should obviously be a GET. Then the filters grow, the URL gets longer, and one day something between the browser and your server gives up.</p><p>One day you learn that hard what that HTTP GET request parameters is typically limited to 2,048 characters (in practice), though the HTTP specification itself sets no official hard limit. So you switch to POST. It works, and you feel a bit dirty about it.</p><p>Here’s a little secret: HTTP now has a proper answer to this problem, and Symfony 7.4 supports it. Let’s talk about QUERY.</p><h3>📮 Postcards and envelopes</h3><p>The post office metaphor works well here.</p><ul><li>GET<strong> is a postcard.</strong> Everything is written on the outside (in the URL) and space is limited. Everyone who handles it (proxies, logs, caches) can read it. It’s safe, meaning it doesn’t change anything, and it’s idempotent, so sending it twice is harmless.</li><li>POST<strong> is an envelope.</strong> You can put as much as you want inside it, but the post office assumes you’re <em>sending</em> something: an order, a payment, a change. So it isn’t considered safe or idempotent, and nobody will resend it for you if it gets lost.</li></ul><p>What we were missing was an <strong>envelope stamped “read-only”</strong>. That’s exactly what QUERY is: a body like POST, with the guarantees of GET.</p><h3>🗺️ The story</h3><p>At Antistatique we built <a href="https://antistatique.net/projets/smarter-planification-territoriale-antenne-region-valais-romand">Smarter</a> for the Antenne Région Valais romand. It’s a platform that gathers everything related to territorial planning: agglomeration projects, inter-municipal master plans, and thousands of <strong>measures</strong> (a new bus stop, a footbridge, a village crossing redesign…).<br><a href="https://antistatique.net/projets/smarter-planification-territoriale-antenne-region-valais-romand">Smarter</a> also provides decision <strong>cockpits</strong>: dashboards per agglomeration or perimeter, full of heavy statistical charts. Users can explore <em>which measures were used to compute each part of a chart</em>. Under the hood it goes like this:</p><ol><li>The backend returns the chart data, and for each segment, the list of measure UUIDs behind it</li><li>When the user clicks a segment, the frontend sends those UUIDs to the catalog endpoint to list the measures.</li></ol><p>It’s a read, so we started with a GET:</p><pre>GET /api/catalog/measures?ids[]=0f8fad5b-d9cb-469f-a165-70867728950e&amp;ids[]=7c9e6679-7425-40de-944b-e07fc1f90ae7&amp;…</pre><p>But sometimes one part of a chart covers <strong>more than 100 measures</strong>. One UUID with its ids%5B%5D= prefix and separator is roughly 45 characters, so 100 of them already add up to around 4.5 KB of URL.</p><blockquote>The postcard was full.</blockquote><p>Sooner or later, we would hit the limit and the request would fail.</p><h3>✉️ The old way</h3><p>So we did what everybody does and switched to an envelope:</p><pre>// POST, because the UUIDs don&#39;t fit in the URL anymore.<br>#[Route(&#39;/api/catalog/measures/search&#39;, methods: [&#39;POST&#39;])]<br>public function search(Request $request): JsonResponse<br>{<br>    $ids = $request-&gt;getPayload()-&gt;all(&#39;ids&#39;);<br>    return $this-&gt;json($this-&gt;catalog-&gt;findByUuids($ids));<br>}</pre><pre>const response = await fetch(&#39;/api/catalog/measures/search&#39;, {<br>  method: &#39;POST&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({ ids: uuids }),<br>});</pre><p>It works, but it’s a small lie:</p><ul><li>The method says “I might change something”, even though we only read.</li><li>Clients, proxies and retry logic can’t safely replay the request.</li><li>Caches ignore it.</li></ul><h3>🔎 The new way</h3><p>With Symfony 7.4, we keep the envelope and stamp it “read-only”:</p><pre>// QUERY: a body like POST, the semantics of GET<br>#[Route(&#39;/api/catalog/measures/search&#39;, methods: [&#39;QUERY&#39;])]<br>public function search(Request $request): JsonResponse<br>{<br>    $ids = $request-&gt;getPayload()-&gt;all(&#39;ids&#39;);<br>    return $this-&gt;json($this-&gt;catalog-&gt;findByUuids($ids));<br>}</pre><pre>// Next.js side: only the method changes<br>const response = await fetch(&#39;/api/catalog/measures/search&#39;, {<br>  method: &#39;QUERY&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({ ids: uuids }),<br>});</pre><p>The diff is tiny, but now the endpoint is honest. Everybody in the chain knows it&#39;s safe to retry.</p><blockquote>Bonus: if you send form-encoded bodies instead of JSON, Symfony 7.4 on PHP 8.4 now parses the body for non-POST methods too (thanks to PHP 8.4 request_parse_body()). So $request-&gt;request-&gt;all(&#39;ids&#39;) works with QUERY exactly as it does with POST.</blockquote><h3>⚠️ Before you rewrite all your endpoints</h3><p>QUERY is a finished standard now, but the ecosystem is still catching up. Before switching in production:</p><ul><li><strong>Check every layer in front of your app.</strong> Reverse proxy, WAF, CDN and API gateway all need to let an unknown-to-them method through. Some will reject it or return a 405.</li><li><strong>CORS.</strong> QUERY isn’t a “simple” method, so cross-origin calls from your frontend will trigger a preflight. Make sure Access-Control-Allow-Methods includes it.</li><li><strong>Caching.</strong> The spec allows QUERY responses to be cached (the body becomes part of the cache key), but most caches don’t support that yet. Don’t count on it for now.</li><li><strong>Your API docs and tools.</strong> Check that your OpenAPI tooling, your HTTP client, and your colleagues’ Postman all know about it.</li></ul><h3>📨 Wrapping up</h3><p>For years we had to choose between a correct GET that broke and a working POST that lied. QUERY removes that trade-off, and Symfony 7.4 makes it a one-word change in your route.</p><p>What you can do now: look for your POST /something/search endpoints that only read data. They&#39;re your first QUERY candidates.</p><p>❤️ Love on your keyboards.</p><h3>Sources</h3><p><strong>J. Reschke, J.M. Snell &amp; M. Bishop</strong> (June 2026) — RFC 10008: The HTTP QUERY Method<br><a href="https://www.rfc-editor.org/info/rfc10008/">https://www.rfc-editor.org/info/rfc10008</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3150623a2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pixel perfect… ou presque]]></title>
            <link>https://wengerk.medium.com/pixel-perfect-ou-presque-b79637968bc9?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b79637968bc9</guid>
            <category><![CDATA[core-web-vitals]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[dithering]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 14:43:20 GMT</pubDate>
            <atom:updated>2026-06-03T14:43:20.427Z</atom:updated>
            <content:encoded><![CDATA[<p>En 2026, il existe trois formats majeurs pour afficher une image sur le Web : <strong>JPEG</strong> (et ses cousins <em>PNG</em> et <em>GIF</em>), <strong>WebP</strong> et <strong>AVIF</strong>. Trois formats, trois époques, trois philosophies.</p><figure><img alt="Un chat allongé qui regarde l’objectif avec de grands yeux expressifs, photographié en noir et blanc avec un effet de trame (dithering), ce qui lui donne un rendu graphique et vintage." src="https://cdn-images-1.medium.com/max/1000/1*fQU0OncW2fPKIkzjwp5m0A.png" /><figcaption>Étrange image, non ? On vous en dit plus dans cet article 😉</figcaption></figure><p>Ces formats ne coexistent pas par hasard. Chacun est le fruit d’une avancée technologique. Le <strong>JPEG</strong>, lui, est le vétéran — universel, fiable, supporté par absolument tous les navigateurs depuis des décennies. <strong>WebP</strong> et <strong>AVIF</strong>, eux, sont bien plus récents, et de fait, tous les navigateurs (et Cloud Provider) ne les supportent pas encore… mais on y reviendra. 😉</p><p>Avant de parler format, j’aimerais vous expliquer pourquoi ce sujet est loin d’être anodin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4H9KMenMwpjx_n0-.jpg" /><figcaption>Les trois métriques Core Web Vitals -LCP, INP et CLS — sont directement impactées par le poids et le chargement des images.</figcaption></figure><blockquote>Pas encore abonné à Medium ? <a href="https://wengerk.medium.com/b79637968bc9?source=friends_link&amp;sk=88b57f558f7a823efa5f90e3f7290a10"><strong>Accédez à cet article gratuitement en cliquant ici</strong></a></blockquote><h3>Pourquoi les formats d’images, c’est critique</h3><p>Voici une vérité que l’on sous-estime trop souvent : <strong>les images sont responsables d’une part énorme du poids d’une page web</strong>. Et le poids d’une page, ça impacte directement sa vitesse de chargement. Et la vitesse de chargement ? Google la surveille de très près.</p><p>Via les <a href="https://www.corewebvitals.io/core-web-vitals">Core Web Vitals</a>, Google pénalise sévèrement les sites lents dans son référencement. Et les images sont en première ligne : selon le <a href="https://almanac.httparchive.org/en/2025/performance">2025 Web Almanac</a>, elles sont responsables du <strong>Largest Contentful Paint (LCP)</strong> sur 85% des pages desktop et 76% des pages mobile. Autrement dit, optimiser ses images est probablement <strong>la chose la plus impactante</strong> que vous puissiez faire pour votre performance web et donc pour votre SEO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8RqKEtNwkTPt0l6L.png" /><figcaption>De la page blanche à l’image chargée : la différence entre FCP (First Contentful Paint) et LCP (Largest Contentful Paint) illustre à quel point une image lente plombe l’expérience utilisateur.</figcaption></figure><p>Pour résoudre ce problème, deux règles d’or :</p><ol><li><strong>Compresser les images</strong> dans un format moderne et performant.</li><li><strong>Servir la bonne taille</strong> d’image selon l’écran de l’utilisateur.</li></ol><p>Commençons par la compression.</p><h3>WebP, AVIF : la révolution de la compression</h3><p>Le constat est brutal : un JPEG de <strong>3 Mo</strong> peut descendre à <strong>600 Ko avec AVIF</strong>, à qualité visuelle identique. WebP, lui, serait cantoné à <strong>1.95 Mo. </strong>En bref,<strong> </strong>WebP compresse environ 25% mieux que JPEG, AVIF va encore plus loin avec jusqu’à 50%-80% de gain.</p><p>C’est une réduction de taille qui change fondamentalement l’équation de performance.</p><blockquote><em>🔬 Vous pouvez le vérifier par vous-même avec notre comparateur en ligne de compression et de qualité d’image : </em><a href="https://antistatique.github.io/images/">https://antistatique.github.io/images</a></blockquote><h3>Mais compresser ne suffit pas</h3><p>Imaginez servir une image de 4000 pixels de large à un utilisateur sur mobile, là où elle n’occupe que 400px à l’écran. C’est 100× de pixels inutiles qui transitent sur le réseau. Un gâchis monumental et encore une fois, les Core Web Vitals vous le font payer cash.</p><blockquote><strong>La règle est simple : on ne sert jamais une image plus grande que ce qu’elle affiche.</strong></blockquote><h3>Notre process chez Antistatique</h3><p>Pour gérer ça proprement, les équipes design et frontend doivent s’aligner en amont sur deux choses :</p><ul><li>Tous les <strong>ratios d’images</strong> utilisés dans le projet (1:1, 16:9, 4:3…)</li><li>Toutes les <strong>tailles maximales</strong> de chaque emplacement (couverture, teaser, highlight…)</li></ul><p>Avec ces deux informations, on peut calculer toutes les variantes nécessaires. Pour nous aider dans ce travail, nous utilisons simplement un petit script que nous pouvons adapter aux besoins de configuration de chaque technologie.</p><p>Par exemple pour un thème WordPress :</p><pre>// bun run web/app/themes/my-theme/assets/config/images.ts | pbcopy<br><br>const ratios = [&#39;3:2&#39;, &#39;5:6&#39;, &#39;16:9&#39;, &#39;21:9&#39;, &#39;1:1&#39;, &#39;original&#39;];<br>const widths = [30, 256, 384, 690, 750, 828, 1080, 1400, 1920, 2048, 3840];<br>const formats = [&#39;jpg&#39;, &#39;webp&#39;, &#39;avif&#39;];<br><br>const imageStyles: string[] = [];<br><br>for (const ratio of ratios) {<br>  for (const width of widths) {<br>    for (const format of formats) {<br>      if (ratio === &#39;original&#39;) {<br>        imageStyles.push(`          [<br>            &#39;name&#39; =&gt; &#39;original_${width}_${format}&#39;,<br>            &#39;width&#39; =&gt; ${width},<br>            &#39;height&#39; =&gt; 9999,<br>            &#39;crop&#39; =&gt; false,<br>          ],`)<br>      } else {<br>        const [w, h] = ratio.split(&#39;:&#39;).map(Number);<br>        imageStyles.push(`          [<br>            &#39;name&#39; =&gt; &#39;${w}_${h}_${width}_${format}&#39;,<br>            &#39;width&#39; =&gt; ${width},<br>            &#39;height&#39; =&gt; ${Math.round(width*h/w)},<br>            &#39;crop&#39; =&gt; true,<br>          ],`)<br>      }<br>    }<br>  }<br>}<br><br>for (const style of imageStyles) {<br>  console.log(style);<br>}</pre><p>Maintenant, avec cet exemple relativement classique de <strong>5 ratios</strong> d’images fixes et un ratio libre (original), une série de <strong>11 largeurs</strong> pour répondre à la plupart des besoins et <strong>3 formats</strong> d’images pour cibler les navigateurs, on obtient pas moins de <strong>198 fichiers générés par image <em>uploadée !</em></strong></p><p>C’est là qu’on s’est posé la vraie question.</p><h3>Faut-il vraiment générer trois formats ?</h3><p>À l’origine, AVIF est arrivé bien après WebP. Mais en 2026, regardons les chiffres de support navigateur :</p><p><strong>WebP</strong>: <a href="https://caniuse.com/webp">caniuse.com/webp</a></p><ul><li>🌍 Global : <strong>96.39%</strong></li><li>🇨🇭 Suisse : <strong>94.52%</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wujcETy6Sk9auEYlYIw0Uw.png" /></figure><p><strong>AVIF</strong> : <a href="https://caniuse.com/avif">caniuse.com/avif</a></p><ul><li>🌍 Global : <strong>94.89%</strong></li><li>🇨🇭 Suisse : <strong>93.26%</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZN1qtnz6bBZlscOKMltYxQ.png" /></figure><p>L’écart entre les deux ? <strong>Moins de 1 points.</strong> Et AVIF est significativement plus performant que WebP.</p><p>La conclusion s’est imposée d’elle-même : <strong>chez Antistatique, on a décidé en 2026 de complètement abandonner WebP au profit d’AVIF.</strong></p><p>On génère désormais uniquement des variations AVIF pour chaque emplacement et on libère ainsi une quantité considérable d’espace disque qui ne stockait que des images WebP et JPEG jamais ou presque jamais servie.</p><h3>Mais les ~6% qui ne supportent pas AVIF ?</h3><p>Bonne question. Sans fallback, ces utilisateurs voient… un carré blanc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*G0uX4Hl8h916bGho.jpeg" /><figcaption>Sans fallback, les navigateurs ne supportant pas AVIF affichent… rien. Un carré blanc, là où une image devrait raconter quelque chose.</figcaption></figure><p>Pas idéal. Mais on n’avait pas non plus envie de générer des dizaines de variations JPEG pour <strong>6% des utilisateurs, </strong>ce serait recréer exactement le problème qu’on cherche à résoudre : de l’espace disque gaspillé et un impact écologique réel.</p><p>On avait besoin d’une troisième voie.</p><h3>Entre dans la danse le Dieter</h3><p>L’idée nous est venue du site <a href="https://solar.lowtechmagazine.com/">Low-tech Magazine</a>, un blog hébergé sur un serveur solaire dont l’esthétique assume complètement ses contraintes techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0mymBSMkT7RHPnIpZOnlA.png" /><figcaption>L’effet Dieter en action : une image monochrome, basse résolution, aux allures de vieille photographie argentique. Moins glamour que l’image original, certes mais quelques centaines d’octets à peine, pour un navigateur qui date de Mathusalem.</figcaption></figure><p>Le principe du <strong>Dieter</strong> est simple : on génère <strong>une unique variation</strong> de chaque image, en basse résolution, en monochrome et en PNG, car son poids sera plus faible qu’un JPEG avec aussi peu de couleurs, dans la taille maximale utilisée sur le site.</p><p>Cette image est ultra-légère, même pour une image originale de 5000×4000 pixels. Pas de variation par breakpoint, pas de format optimisé : un seul fichier, minuscule, qui s’affiche sur tous les navigateurs.</p><p>Voici une commande simple pour générer notre image Dieter avec ImageMagick :</p><pre>magick in.jpg -scale 640 -colorspace Gray -ordered-dither h4x4o -colorspace sRGB -opaque black out.png</pre><p>Est-ce que c’est fidèle à l’image original ? Non. Est-ce que c’est lisible ? Absolument. Et surtout : à qui s’adresse-t-on ? À des utilisateurs d’un navigateur sans mise à jour depuis 2019. Ces personnes ont très certainement d’autres défis sur Internet que la qualité d’affichage d’une image 😄.</p><h3>Bilan</h3><p>Notre stack final:</p><ul><li>✅ <strong>AVIF</strong> — variations multi-tailles pour 94%+ des utilisateurs</li><li>✅ <strong>Dieter</strong> — une unique image monochrome low-res pour le reste</li></ul><p>Les bénéfices sont concrets :</p><ul><li>Les <strong>Core Web Vitals</strong> de nos projets restent à 100/100.</li><li>On ne génère <strong>que les images réellement utilisées</strong> par nos utilisateurs.</li><li>On économise des <strong>gigaoctets d’espace disque</strong> qui dormaient inutilement.</li><li>Et on fait un petit geste pour <strong>la planète, </strong>parce que chaque octet évité, c’est de l’énergie économisée.</li></ul><p>Petit spoiler, si vous voulez aller plus loin : on publiera bientôt un article concernant le peut-être futur format du Web JPEG XL. Stay tuned. 🤓</p><p>❤️ Cœur sur vos claviers</p><p><em>Cet article a été co-rédigé avec mon collègue </em><a href="https://medium.com/@yago_0"><em>Yann Gouffon</em></a><em> pour le blog d’</em><a href="https://antistatique.net"><em>Antistatique</em></a><em> — Agence Web à Lausanne et Genève.</em></p><h3>Sources</h3><p><strong>Hardi</strong> (Juin 2025) - Core Web Vitals: How Image Optimization Impacts Your Lighthouse Score.<br><a href="https://dev.to/hardik_b2d8f0bca/core-web-vitals-how-image-optimization-impacts-your-lighthouse-score-3407">https://dev.to/hardik_b2d8f0bca/core-web-vitals-how-image-optimization-impacts-your-lighthouse-score-3407</a></p><p><strong>Kostya Stepanov</strong> (Fév. 2026) - How Web Design Impacts Page Speed and Core Web Vitals.<br><a href="https://medium.com/@Shakuro/how-web-design-impacts-page-speed-and-core-web-vitals-ea441796b5e5">https://medium.com/@Shakuro/how-web-design-impacts-page-speed-and-core-web-vitals-ea441796b5e5</a></p><p><strong>HTTP Archive</strong> (Avr. 2026) - The Web Almanac<strong>.</strong><br><a href="https://almanac.httparchive.org/en/2025/performance#speculation-rules-usage">https://almanac.httparchive.org/en/2025/performance</a></p><p><strong>Andrei Alba</strong> (Nov. 2025) - AVIF vs WebP: Which Modern Image Format Is Better?<br><a href="https://shortpixel.com/blog/avif-vs-webp/">https://shortpixel.com/blog/avif-vs-webp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b79637968bc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autowiring in Drupal - the hidden gem many dev still ignore]]></title>
            <link>https://wengerk.medium.com/autowiring-in-drupal-the-hidden-gem-many-dev-still-ignore-386c6912f596?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/386c6912f596</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Wed, 20 May 2026 07:54:33 GMT</pubDate>
            <atom:updated>2026-05-20T07:54:33.192Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>⚠️ </em><strong><em>Heads up</em></strong><em> — This article is about Dependency Injection in Drupal. If you’re not yet comfortable with DI, services or the service container, some sections might feel a bit abstract. I’d recommend reading this before </em><a href="https://medium.com/@laurentmn/symfony-7-dependency-injection-what-really-happens-behind-the-scenes-de6f6afc1c42"><em>article</em></a><em>.</em></blockquote><p>It’s a random Tuesday, I’m reviewing a pull request and I see the classic DI boilerplate. You know the one.</p><pre>public static function create(ContainerInterface $container): static {<br>  return new static(<br>    $container-&gt;get(&#39;entity_type.manager&#39;),<br>    $container-&gt;get(&#39;current_user&#39;),<br>    $container-&gt;get(&#39;logger.factory&#39;),<br>    $container-&gt;get(&#39;config.factory&#39;)<br>  );<br>}</pre><p>I stare at the screen. I sip my coffee. I think: <em>“We’ve been doing this since Drupal 8. It’s 2024. Symfony has Autowiring since so many years — can’t we have a better way to acheive DI in Drupal ?”</em></p><p>There is. And it’s been available since <strong>Drupal 10.2</strong>.<br>Let me introduce you to <strong>Autowiring for Drupal</strong>.</p><figure><img alt="A stylized illustration on a dark purple background showing a large syringe filled with blue liquid and the Drupal logo injecting into an orange cube marked with the Drupal droplet symbol, representing Dependency Injection in Drupal." src="https://cdn-images-1.medium.com/max/1024/1*lr5BlpRf9rIj99x5AmfrPQ.png" /><figcaption>Injecting Drupal-powered services into a component 💉💧</figcaption></figure><h3>What is Autowiring?</h3><p>In a nutshell, Autowiring is a feature of the Service Container (from Symfony) that allows <strong>automatic dependency injection based on Type Hints</strong>.</p><p>Instead of you manually telling the container <em>“hey, inject this service, then that one, then that other one”</em>, the container figures it out by looking at the type hints in your constructor.<br>It reads your code, sees EntityTypeManagerInterface $entityTypeManager, and goes: <em>&quot;Oh, I know that class! I&#39;ll inject the right service automatically.&quot;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*5kEnoEKnIHJMTerD.jpg" /><figcaption>Magic? Almost. But it’s actually very elegant engineering 🌈</figcaption></figure><p>👨‍🍳 Au menu :</p><ul><li>What DI used to look like in Drupal (and why it was painful)</li><li>How FQCN aliases made Autowiring possible</li><li>How to use Autowiring in Services, Controllers, Forms, Blocks and Hooks</li><li>What to do when Autowiring fails</li></ul><h3>Back in the Day — The Old-School DI in Drupal</h3><p>Before Drupal 10.2, injecting services was a ritual. A repetitive, verbose, copy-paste ritual. Depending on what you were building, you had two flavors of pain.</p><h4>Flavor 1: The services.yml way</h4><p>Every service had a unique name, and every dependency had to be declared explicitly in your module’s services.yml:</p><pre># my_module.services.yml<br>services:<br>  my_module.my_service:<br>    class: Drupal\my_module\MyService<br>    arguments:<br>      - &#39;@entity_type.manager&#39;<br>      - &#39;@current_user&#39;<br>      - &#39;@logger.factory&#39;<br>      - &#39;@config.factory&#39;</pre><p>And then your class would receive those services in the constructor — in the <strong>exact same order</strong> as declared in the YAML. <br>Miss one? Wrong order? Enjoy your ArgumentCountError at runtime 🎉.</p><pre>namespace Drupal\my_module;<br><br>use Drupal\Core\Config\ConfigFactoryInterface;<br>use Drupal\Core\Entity\EntityTypeManagerInterface;<br>use Drupal\Core\Logger\LoggerChannelFactoryInterface;<br>use Drupal\Core\Session\AccountInterface;<br><br>class MyService {<br>  public function __construct(<br>    private readonly EntityTypeManagerInterface $entityTypeManager,<br>    private readonly AccountInterface $currentUser,<br>    private readonly LoggerChannelFactoryInterface $loggerFactory,<br>    private readonly ConfigFactoryInterface $configFactory,<br>  ) {}<br>}</pre><p>Functional? Yes. Maintainable? Questionable. <br>Every time you add a dependency, you update the YAML, the constructor and pray you didn’t swap the order.</p><h4>Flavor 2: The create() method</h4><p>For Controllers, Forms and Blocks (and many others classes that implement ContainerInjectionInterface without using a declaration inservices.yml) Drupal used - and still uses by default - the static create() method:</p><pre>namespace Drupal\my_module\Controller;<br><br>use Drupal\Core\Controller\ControllerBase;<br>use Drupal\Core\Entity\EntityTypeManagerInterface;<br>use Drupal\Core\Session\AccountInterface;<br>use Symfony\Component\DependencyInjection\ContainerInterface;<br><br>class MyController extends ControllerBase {<br><br>  public function __construct(<br>    private readonly EntityTypeManagerInterface $entityTypeManager,<br>    private readonly AccountInterface $currentUser,<br>  ) {}<br><br>  public static function create(ContainerInterface $container): static {<br>    return new static(<br>      $container-&gt;get(&#39;entity_type.manager&#39;),<br>      $container-&gt;get(&#39;current_user&#39;),<br>    );<br>  }<br>}</pre><p>This approach works, but it&#39;s essentially a <strong>service locator anti-pattern.<br></strong>You&#39;re manually pulling services out of the container rather than letting the container inject them. Every new dependency means updating both the constructor <em>and</em> the create() method. <br>Two places. Every. Single. Time.</p><h3>FQCN Aliases</h3><p>Before Autowiring could exist, Drupal needed to lay some groundwork.</p><p>Starting from <strong>Drupal 10.1</strong>, most core services were <strong>aliased using their Fully Qualified Class Name (FQCN)</strong>. What does that mean?</p><p>Previously, a service was only reachable via its unique string identifier, like webprofiler.profiler. You could never refer to it by its class name.</p><pre># Before: only reachable via string identifier<br>webprofiler.profiler:<br>  class: Drupal\webprofiler\Profiler\Profiler<br>  arguments:<br>    - &#39;@webprofiler.file_storage&#39;<br>    - &#39;@logger.channel.webprofiler&#39;<br>    - &#39;@config.factory&#39;</pre><p>With FQCN aliases, the same service becomes also accessible via its class name:</p><pre># After: also reachable via the FQCN<br>webprofiler.profiler:<br>  class: Drupal\webprofiler\Profiler\Profiler<br>  arguments:<br>    - &#39;@webprofiler.file_storage&#39;<br>    - &#39;@logger.channel.webprofiler&#39;<br>    - &#39;@config.factory&#39;<br><br># This alias makes autowiring possible ✨<br>Drupal\webprofiler\Profiler\Profiler: &#39;@webprofiler.profiler&#39;</pre><p>When a service name equals the FQCN of the service class, the container can <strong>automatically resolve and inject dependencies</strong> simply by matching the type hint. <br><strong>That&#39;s Autowiring</strong>.</p><h3>Autowiring in Services</h3><p>With Autowiring, that verbose services.yml we saw earlier becomes almost whisper-quiet:</p><p><strong>Old way:</strong></p><pre>services:<br>  webprofiler.profiler_listener:<br>    class: Drupal\webprofiler\EventListener\ProfilerListener<br>    arguments:<br>      - &#39;@webprofiler.profiler&#39;<br>      - &#39;@request_stack&#39;<br>      - &#39;@webprofiler.matcher.exclude_path&#39;</pre><p><strong>With Autowiring:</strong></p><pre>services:<br>  _defaults:<br>    autowire: true  # ✨ Enable autowiring for all services in this file<br><br>  # The FQCN is both the service name and the alias<br>  Drupal\webprofiler\EventListener\ProfilerListener: ~</pre><p>This works because:</p><ol><li>The service is registered using its FQCN as the service name (which also serves as the alias)</li><li>The container reads the constructor type hints and injects the matching services automatically</li></ol><p>Your class doesn’t change at all, the constructor type hints do all the talking:</p><pre>namespace Drupal\webprofiler\EventListener;<br><br>use Drupal\webprofiler\Matcher\ExcludePathRequestMatcher;<br>use Drupal\webprofiler\Profiler\Profiler;<br>use Symfony\Component\HttpFoundation\RequestStack;<br><br>class ProfilerListener {<br>  public function __construct(<br>    // The container resolves these automatically via their FQCN aliases ✨<br>    private readonly Profiler $profiler,<br>    private readonly RequestStack $requestStack,<br>    private readonly ExcludePathRequestMatcher $excludePathMatcher,<br>  ) {}<br>}</pre><h4>Autowiring in Controllers</h4><p>Starting from <strong>Drupal 10.2</strong>, ControllerBase uses the AutowireTrait. This means you can finally <strong>delete that </strong><strong>create() method</strong> and let the container do its job.</p><p><strong>Old way</strong></p><pre>class DashboardController extends ControllerBase {<br><br>  public function __construct(<br>    private readonly Profiler $profiler,<br>    private readonly TemplateManager $templateManager,<br>  ) {}<br><br>  // Goodbye, old friend. We won&#39;t miss you. 👋<br>  public static function create(ContainerInterface $container): static {<br>    return new static(<br>      $container-&gt;get(&#39;webprofiler.profiler&#39;),<br>      $container-&gt;get(&#39;webprofiler.template_manager&#39;),<br>    );<br>  }<br>}</pre><p><strong>With Autowiring (Drupal 10.2+)</strong></p><pre>use Drupal\Core\Controller\ControllerBase;<br>use Drupal\Core\DependencyInjection\AutowireTrait;<br><br>class DashboardController extends ControllerBase {<br><br>  // ✨ That&#39;s it. No more create() method.<br>  use AutowireTrait; <br><br>  public function __construct(<br>    private readonly Profiler $profiler,<br>    private readonly TemplateManager $templateManager,<br>  ) {}<br><br>  // No create() method needed anymore. 🎉<br>}</pre><p>The AutowireTrait can be used on <strong>any class that implements </strong><strong>ContainerInjectionInterface</strong>.</p><h4>Autowiring in Forms</h4><p>FormBase does not yet use AutowireTrait by default (yes, it&#39;s 2026, I know 😅), but you can <strong>manually add the trait</strong> to your custom forms.</p><pre>namespace Drupal\my_module\Form;<br><br>use Drupal\Core\DependencyInjection\AutowireTrait;<br>use Drupal\Core\Entity\EntityTypeManagerInterface;<br>use Drupal\Core\Form\FormBase;<br>use Drupal\Core\Form\FormStateInterface;<br><br>class MyForm extends FormBase {<br><br>  // ✨ Just add this and you&#39;re done.<br>  use AutowireTrait; <br><br>  public function __construct(<br>    private readonly EntityTypeManagerInterface $entityTypeManager,<br>  ) {}<br>}</pre><h4>Autowiring in Blocks</h4><p>Blocks (which implement ContainerFactoryPluginInterface) also benefit from AutowireTrait. <br>The pattern is the same: add the trait, remove the create() method:</p><pre>namespace Drupal\my_module\Plugin\Block;<br><br>use Drupal\Core\Block\Attribute\Block;<br>use Drupal\Core\Block\BlockBase;<br>use Drupal\Core\DependencyInjection\AutowireTrait;<br>use Drupal\Core\Entity\EntityTypeManagerInterface;<br>use Drupal\Core\Plugin\ContainerFactoryPluginInterface;<br>use Drupal\Core\StringTranslation\TranslatableMarkup;<br><br>#[Block(<br>  id: &#39;my_module_my_block&#39;,<br>  admin_label: new TranslatableMarkup(&#39;My Block&#39;),<br>)]<br>class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {<br><br>  // ✨ Replaces the create() method.<br>  use AutowireTrait; <br><br>  public function __construct(<br>    array $configuration,<br>    string $plugin_id,<br>    mixed $plugin_definition,<br>    private readonly EntityTypeManagerInterface $entityTypeManager,<br>  ) {<br>    parent::__construct($configuration, $plugin_id, $plugin_definition);<br>  }<br>}</pre><h4>Autowiring in Hooks</h4><p>Starting from <strong>Drupal 11.1</strong>, hooks can be defined inside classes using the #[Hook] attribute.<br>And the best part? All hook classes are <strong>automatically registered as autowired services</strong>. You don&#39;t need to configure anything in services.yml.</p><pre>namespace Drupal\file\Hook;<br><br>use Drupal\Core\Entity\EntityFieldManagerInterface;<br>use Drupal\Core\Entity\EntityTypeManagerInterface;<br>use Drupal\field\Entity\FieldStorageConfig as FieldStorageConfigInterface;<br>use Drupal\views\EntityViewsDataProvider as FieldViewsDataProvider;<br>use Drupal\Core\Hook\Attribute\Hook;<br><br>class FileViewsHooks {<br><br>  // All dependencies are autowired automatically. 💫<br>  public function __construct(<br>    protected readonly EntityTypeManagerInterface $entityTypeManager,<br>    protected readonly EntityFieldManagerInterface $entityFieldManager,<br>    protected readonly ?FieldViewsDataProvider $fieldViewsDataProvider,<br>  ) {}<br><br>  #[Hook(&#39;field_views_data&#39;)]<br>  public function fieldViewsData(FieldStorageConfigInterface $field_storage): array {}<br>}</pre><p>No services.yml. No create(). <br>No manual wiring. Just clean, readable PHP.</p><p>I wrote a dedicated article about <a href="https://wengerk.medium.com/drupal-object-oriented-hooks-989caf751e5b">Object-Oriented Hooks</a> in Drupal if you want to go deeper.</p><h3>When Autowiring fails</h3><p>Not all services can be autowired automatically. You might have seen this terrifying screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KiTrL_h5XEnvp5NN.png" /><figcaption>The <em>AutowiringFailedException</em></figcaption></figure><blockquote>Why does this happen? Because <strong>some interfaces have multiple implementations or they don’t use FQCN alias</strong>.<br>LoggerInterface is the perfect example: Drupal has dozens of logger channels (logger.channel.php, logger.channel.drupal, logger.channel.your_module…). The container doesn&#39;t know which one you want, so instead of guessing, it throws an exception.</blockquote><p>In this case, you can use the <strong>#[Autowire] attribute</strong> to explicitly specify which service to inject:</p><pre>namespace Drupal\my_module;<br><br>use Psr\Log\LoggerInterface;<br>use Symfony\Component\DependencyInjection\Attribute\Autowire;<br><br>class MyService {<br><br>  public function __construct(<br>    // ✨ Tell the container exactly which logger channel to inject.<br>    #[Autowire(service: &#39;logger.channel.my_module&#39;)]<br>    private readonly LoggerInterface $logger,<br>  ) {}<br>}</pre><p>Think of #[Autowire] as leaving a post-it note for the container: <em>&quot;Yes I know there are many </em><em>LoggerInterface implementations , use THIS specific one.&quot;</em></p><p>Other cases where you might need #[Autowire]:</p><ul><li><strong>Tagged services</strong> — when you want a collection of services sharing a tag, injected as an iterable.</li><li><strong>Services without a FQCN alias</strong> — when an older or contributed service is still registered only under its legacy string identifier and hasn&#39;t been aliased yet.</li></ul><h3>Conclusion</h3><p>Autowiring isn’t a revolutionary new concept, Symfony has had it for years. But it finally landed properly in Drupal with 10.2 and continue to be implemented in Drupal 11+. <br>It will genuinely changes how you write code day to day.</p><p>Less boilerplate. Fewer opportunities to introduce bugs (wrong order in create()? wrong service name?). More readable, maintainable code.<br>Your constructor becomes the single source of truth for your dependencies the way it always should have been.</p><p>Yes, it arrived quite a long time ago on Drupal, drop by drop. But it’s here now, it’s used by the Core and there’s no good reason not to use it on your next project.</p><p>If you’re maintaining older Drupal modules, this is also a great refactoring opportunity, removing create() methods one by one is surprisingly satisfying. Trust me.</p><p>❤️ Love on your keyboards</p><h3>Sources</h3><p><strong>Drupal.org</strong> (Oct 2023), Controllers can be autowired and a create() method is no longer always necessary.<br><a href="https://www.drupal.org/node/3395716">https://www.drupal.org/node/3395716</a></p><p><strong>Drupal.org</strong> (June 2021), Services can be autowired.<br><a href="https://www.drupal.org/node/3218156">https://www.drupal.org/node/3218156</a></p><p><strong>Drupal.org</strong> (June 2023), Autowiring is enabled in core.services.yml.<br><a href="https://www.drupal.org/node/3366757">https://www.drupal.org/node/3366757</a></p><p><strong>Drupal.org</strong> (Feb 2026), Dependency Injection in a form.<br><a href="https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/dependency-injection-in-a-form">https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/dependency-injection-in-a-form</a></p><p><strong>Drupal.org</strong> (Oct 2024), Support for object oriented hook implementations using autowired services.<br><a href="https://www.drupal.org/node/3442349">https://www.drupal.org/node/3442349</a></p><p><strong>Drupal.org</strong> (Jan 2026), Add create() factory method with autowired parameters to PluginBase.<br><a href="https://www.drupal.org/project/drupal/issues/3452852">https://www.drupal.org/project/drupal/issues/3452852</a></p><p><strong>Kevin Wenger </strong>(Sept 2025), Drupal Object-Oriented Hooks.<br><a href="https://wengerk.medium.com/drupal-object-oriented-hooks-989caf751e5b">https://wengerk.medium.com/drupal-object-oriented-hooks-989caf751e5b</a></p><p><strong>Jane</strong> (May 2023), Can services be autowired?.<br><a href="https://drupal.stackexchange.com/questions/315397/can-services-be-autowired">https://drupal.stackexchange.com/questions/315397/can-services-be-autowired</a></p><p><strong>Luca Lusso</strong> (Dec 2025), Drupal service container deep dive (Part 2): aliases, autowiring, and named arguments.<br><a href="https://tech.sparkfabrik.com/en/blog/drupal-service-container-deep-dive-part-2/">https://tech.sparkfabrik.com/en/blog/drupal-service-container-deep-dive-part-2/</a></p><p><strong>Brian Walters</strong> (Oct 2018), Symfony 4 Autowiring in a Nutshell.<br><a href="https://medium.com/@BDubCodes/symfony-4-autowiring-in-a-nutshell-23a80b15ec80">https://medium.com/@BDubCodes/symfony-4-autowiring-in-a-nutshell-23a80b15ec80</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=386c6912f596" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a Custom Views Pseudo Field on Drupal]]></title>
            <link>https://wengerk.medium.com/how-to-create-a-custom-views-pseudo-field-on-drupal-0c4240acdc50?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c4240acdc50</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 07:55:18 GMT</pubDate>
            <atom:updated>2026-03-02T07:55:18.466Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Every multilingual Drupal project eventually runs into the same quiet frustration: your Admin View shows all content (including translated ones) and contributors lose track of which content is the original and which are its translations. The fix is a Views pseudo field — a field that appears in the Views UI like any other, but computes its output at render time rather than reading from a database column. In this article I am going to show you how to create one from scratch.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNekgZb_6SqpnXGDsJdEtQ.png" /><figcaption>The Content View listing Nodes. A <em>Title (original language)</em> pseudo field would make it immediately clear which entries are translations from the original content.</figcaption></figure><p><strong>Scope:</strong> I will <em>not</em> explain how to create a custom field for a node (i.e. a FieldType/FieldFormatter/FieldWidget Plugin). The focus here is exclusively on creating a field that appears and is rendered <em>inside a View</em> — a so-called pseudo field.</p><p><em>Not a Medium member yet? </em><a href="https://medium.com/@wengerk/how-to-create-a-custom-views-pseudo-field-on-drupal-0c4240acdc50"><em>Click here to access this article for free</em></a><em>!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_27M0OY8qEKt43XVc3fYwg.png" /><figcaption>Let’s dive into Drupal Views</figcaption></figure><p>By default, Views module can display data contained in any field attached to an entity that is exposed in Views, and the content of any database column exposed to Views via an implementation of hook_views_data().</p><p>It’s possible to create <strong>pseudo fields</strong>. These appear in the Views UI like any other field, but don’t map exclusively to the data in a database.<br>Instead, they allow the data to be <strong>preprocessed</strong> at render time.<br>This could mean performing a calculation, combining multiple fields into one, loading related entity data or anything else you can express in Drupal.</p><p><strong>The mechanism works in two steps:</strong></p><p>1. First, you use hook_views_data_alter (or hook_views_data) to register your pseudo field against a base table — telling Views “this field exists and here is its plugin ID”.</p><p>2. Second, you provide the corresponding <strong>Views field plugin</strong> class that implements the actual logic.</p><h3>The code</h3><p>For this article, I will build a pseudo field that displays a node’s title in its original source language. The standard Views Title field renders in the currently active interface language, which means translated nodes and their source all look identical in the listing. A dedicated <em>Title (original language)</em> column solves that instantly.</p><p>The code in this article targets <strong>Drupal 11</strong>. It uses <strong>Object-Oriented Hooks</strong>, a modern way to implement Drupal hooks introduced in recent Drupal release that replaces procedural mymodule.module functions with dedicated PHP classes.</p><blockquote>If you are not yet familiar with Drupal Object-Oriented Hooks, I strongly recommend reading this article: <a href="https://wengerk.medium.com/drupal-object-oriented-hooks-989caf751e5b">Drupal Object-Oriented Hooks</a>. It explains the #[Hook] attribute pattern that we will use throughout this article.</blockquote><p>The examples use the module machine name my_module. Replace this with your own module&#39;s machine name throughout.</p><h4>Step 1 — Register the Pseudo Field via hook_views_data_alter()</h4><p>Views discovers available fields by scanning the data registered through hook_views_data and hook_views_data_alter. We use the <em>alter</em> variant here because we want to attach our pseudo field to an existing base table — node_field_data — that is already registered by Drupal core.</p><p>The field.id key in the registration array is the plugin ID of our Views field plugin. We will create that plugin in the next step.</p><pre>&lt;?php<br><br>namespace Drupal\my_module\Hook;<br><br>use Drupal\Core\Hook\Attribute\Hook;<br>use Drupal\Core\StringTranslation\StringTranslationTrait;<br><br>/**<br> * Hook Views Data implementations.<br> */<br>#[Hook(&#39;views_data_alter&#39;)]<br>final class ViewsData {<br><br>  use StringTranslationTrait;<br><br>  /**<br>   * Implements hook_views_data_alter().<br>   *<br>   * Registers the my_module_node_original_title field on the node_field_data<br>   * base table so it is available in any View that uses Content as its base.<br>   */<br>  public function __invoke(array &amp;$data): void {<br>    $data[&#39;node_field_data&#39;][&#39;my_module_node_original_title&#39;] = [<br>      &#39;title&#39; =&gt; $this-&gt;t(&#39;Title (original language)&#39;),<br>      &#39;help&#39;  =&gt; $this-&gt;t(&#39;The node title rendered in its original (source) language, regardless of the current interface language.&#39;),<br>      &#39;field&#39; =&gt; [<br>        &#39;id&#39; =&gt; &#39;my_module_node_original_title&#39;,<br>      ],<br>    ];<br>  }<br>}</pre><h4>Step 2 — Implement the Views Field Plugin</h4><p>Now we need the actual plugin that Views will call to render our field.<br>All Views field plugins extend FieldPluginBase and are placed in src/Plugin/views/field/.</p><p>The key methods we override are:</p><ul><li><strong>query()</strong> — called by Views when building the SQL query. Because our field does not need an extra database column (we retrieve the data from the already-loaded entity), we leave this empty.</li><li><strong>render()</strong> — called for each row in the result set. This is where we retrieve the node entity from the result row and return its untranslated title using getUntranslated()-&gt;getTitle().</li><li><strong>usesGroupBy()</strong> — we return FALSE because grouping by a computed pseudo field does not make sense.</li></ul><pre>&lt;?php<br><br>namespace Drupal\my_module\Plugin\views\field;<br><br>use Drupal\node\NodeInterface;<br>use Drupal\views\Attribute\ViewsField;<br>use Drupal\views\Plugin\views\field\FieldPluginBase;<br>use Drupal\views\ResultRow;<br><br>/**<br> * A Views field that always renders the node title in its original language.<br> *<br> * Useful when Views is displaying a translated context but the original<br> * (source) language title is needed regardless of the current UI language.<br> */<br>#[ViewsField(&#39;my_module_node_original_title&#39;)]<br>final class NodeOriginalTitle extends FieldPluginBase {<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  #[\Override]<br>  public function query(): void {<br>    // No extra query needed — the title is fetched from the loaded entity.<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  #[\Override]<br>  public function render(ResultRow $values): string {<br>    $entity = $this-&gt;getEntity($values);<br><br>    if (!$entity instanceof NodeInterface) {<br>      return &#39;&#39;;<br>    }<br><br>    return $entity-&gt;getUntranslated()-&gt;getTitle() ?? &#39;&#39;;<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  #[\Override]<br>  public function usesGroupBy(): bool {<br>    return FALSE;<br>  }<br><br>}</pre><h3>Wrapup</h3><p>After completing all steps, your module directory should contain these new files alongside your existing ones:</p><pre>web/modules/custom/my_module/<br>├── my_module.info.yml                       # updated: added drupal:views dependency<br>└── src/<br>    ├── Hook/<br>    │   └── ViewsData.php                    # new: hook_views_data_alter() implementation<br>    └── Plugin/<br>        └── views/<br>            └── field/<br>                └── NodeOriginalTitle.php    # new: Views field plugin</pre><p>Once the field is added to the Content View, editors will see a dedicated column showing the original language title for every node row — regardless of which language the interface is currently set to. Pair it with the standard Title column and the distinction between source content and its translations becomes immediately obvious at a glance, no content-opening required.</p><p>A small addition to your codebase, but a meaningful improvement to the daily editorial experience.</p><p>❤️ Love on your keyboards.</p><h3>Sources</h3><p><strong>Drupalize Me</strong> (October 2024) — Define a Custom Views Pseudo Field Plugin.<br><a href="https://drupalize.me/tutorial/define-custom-views-pseudo-field-plugin">https://drupalize.me/tutorial/define-custom-views-pseudo-field-plugin</a></p><p><strong>Daniel Sipos</strong> (June 2015) — Creating a custom Views field in Drupal 8.<br><a href="https://www.webomelette.com/creating-custom-views-field-drupal-8">https://www.webomelette.com/creating-custom-views-field-drupal-8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c4240acdc50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tilling 360° Panoramas with Symfony & ImageMagick]]></title>
            <link>https://wengerk.medium.com/tilling-360-panoramas-with-symfony-imagemagick-da9d34fa9832?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9d34fa9832</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 06:47:00 GMT</pubDate>
            <atom:updated>2026-05-20T07:55:13.335Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had to create a solution to automate chunking 360° panoramic images for my side-project <strong>Respawwwn. </strong>For those who don’t know <a href="https://respawwwn.com/">Respawwwn</a> yet, it’s a daily video-game quiz (GameGuesser) that tests your video game expertise with game Panorama to guess. A real challenge for gaming enthusiasts ! 👾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LA96n-xMTd0u8sEsxOcftQ.jpeg" /><figcaption>360° tiny planet of Myst</figcaption></figure><p>One of the complex technical challenges I had to deal with is the <strong>size of panoramas</strong>. Indeed, a panorama file can be pretty huge — we’re talking 10&#39;000×6&#39;000 pixels, with final file sizes may reach up to 20MB quickly.</p><p>As I want <strong>Respawwwn</strong> to be playable on any device with any connection, instead of loading one massive image upfront, I had the idea to <strong>chunk my panorama into tiles</strong>. The reasoning is simple: in a 360° viewer, you don’t see the whole image before moving your head. So why load it all at once?</p><p><em>Not a Medium member yet? </em><a href="https://medium.com/@wengerk/tilling-360-panoramas-with-symfony-imagemagick-da9d34fa9832"><em>Click here to access this article for free</em></a><em>!</em></p><blockquote>This approach reduced initial loading and Time to Interactive by up to 80%! 🚀</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FYb_Nu0JrMO4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fshorts%2FYb_Nu0JrMO4&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FYb_Nu0JrMO4%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/831393d3e3dc8a3faf5ae6c7b28dfd0e/href">https://medium.com/media/831393d3e3dc8a3faf5ae6c7b28dfd0e/href</a></iframe><h3><strong>Why it works</strong></h3><p>Let me explain why this technique is clever. When you’re viewing a 360° panorama, you’re essentially looking through a small window into a much larger sphere. At any given moment, you only see a fraction of the total image — typically around 10–20% depending on your field of view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*sAaC1tv4REjg58fv01OZvA.png" /><figcaption>The viewing sphere. The FOV (blue region) is to be mapped to a rectangular image. <strong><em>o</em></strong> is the observers position, in the center of the sphere.</figcaption></figure><p>Think about it like Google Maps. You don’t download the entire world map when you open the app. Instead, the system loads only the tiles you’re currently viewing, plus maybe a few surrounding ones for smooth panning. The same principle applies perfectly to panoramic images.</p><p>Let’s say you have a panorama of 12&#39;000×6&#39;000 pixels. The full image might weigh around 14MB. But if you split it into 128 tiles (16 columns × 8 rows), each tile becomes roughly 750×750 pixels, weighing around 20–100KB each.</p><p>When a user first loads the panorama, they might only need 8–12 tiles to fill their current view. That’s approximately <strong>600KB–1.2MB instead of 14MB</strong> — a massive improvement for mobile users or those with slower connections.</p><p>The best part? As the user rotates the view, you can progressively load additional tiles in the background. By the time they look in a new direction, the tiles are already there. It’s seamless.</p><h4>The Tile Naming Convention</h4><p>When we generate tiles, we follow a sequential naming pattern:</p><pre>tile_000.jpg  tile_001.jpg  tile_002.jpg  ... tile_015.jpg   (Row 1: cols 0-15)<br>tile_016.jpg  tile_017.jpg  tile_018.jpg  ... tile_031.jpg   (Row 2: cols 0-15)<br>...<br>tile_112.jpg  tile_113.jpg  tile_114.jpg  ... tile_127.jpg   (Row 8: cols 0-15)</pre><p>The viewer can then reconstruct the panorama by calculating: tile_index = row * cols + col</p><h3>The Command</h3><p>Let&#39;s dive into the implementation. This command will split a single panorama image into 128 tiles (16 columns × 8 rows).</p><pre>&lt;?php<br><br>namespace App\Command;<br><br>use Symfony\Component\Console\Attribute\AsCommand;<br>use Symfony\Component\Console\Command\Command;<br>use Symfony\Component\Console\Input\InputInterface;<br>use Symfony\Component\Console\Input\InputOption;<br>use Symfony\Component\Console\Output\OutputInterface;<br>use Symfony\Component\Console\Style\SymfonyStyle;<br>use Symfony\Component\Process\Process;<br><br>#[AsCommand(<br>    name: &#39;app:image:tiler&#39;,<br>    description: &#39;Generate tiles from an image using ImageMagick.&#39;,<br>)]<br>class PanoramaTilerCommand extends Command<br>{<br>    /**<br>     * Number of tile columns to generate (width division).<br>     */<br>    private const TILE_COLS = 16;<br><br>    /**<br>     * Number of tile rows to generate (height division).<br>     */<br>    private const TILE_ROWS = 8;<br><br>    /**<br>     * Naming pattern for generated tiles (tile_000, tile_001, etc.).<br>     */<br>    private const TILE_PATTERN = &#39;tile_%03d&#39;;<br><br>    protected function configure(): void<br>    {<br>        $this<br>            -&gt;addOption(<br>                &#39;file&#39;,<br>                &#39;f&#39;,<br>                InputOption::VALUE_REQUIRED,<br>                &#39;Image file to process.&#39;<br>            )<br>            -&gt;addOption(<br>                &#39;destination&#39;,<br>                &#39;dest&#39;,<br>                InputOption::VALUE_REQUIRED,<br>                &#39;Destination directory for tiles.&#39;<br>            );<br>    }<br><br>    protected function execute(InputInterface $input, OutputInterface $output): int<br>    {<br>        $io = new SymfonyStyle($input, $output);<br>        $io-&gt;title(&#39;Panorama Tiles Generation&#39;);<br><br>        // Check if ImageMagick is available.<br>        if (!$this-&gt;isImageMagickAvailable()) {<br>            $io-&gt;error(&#39;ImageMagick is not available. Please install ImageMagick.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        $file = $input-&gt;getOption(&#39;file&#39;);<br>        $dest = $input-&gt;getOption(&#39;destination&#39;);<br><br>        // Validate input file.<br>        if (!$file || !is_file($file)) {<br>            $io-&gt;error(&#39;Image file does not exist or was not provided.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        // Validate destination directory.<br>        if (!$dest) {<br>            $io-&gt;error(&#39;Destination directory was not provided.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        // Check if destination already has tiles.<br>        if ($this-&gt;destinationHasTiles($dest)) {<br>            $io-&gt;error(&#39;Destination directory already contains tiles. Please clean it first or use a different directory.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        // Create destination directory if it doesn&#39;t exist.<br>        if (!is_dir($dest)) {<br>            if (!mkdir($dest, 0755, true)) {<br>                $io-&gt;error(&#39;Failed to create destination directory.&#39;);<br><br>                return Command::FAILURE;<br>            }<br>        }<br><br>        // Get file extension from source image.<br>        $extension = pathinfo($file, PATHINFO_EXTENSION);<br>        if (!$extension) {<br>            $extension = &#39;jpg&#39;; // Fallback to jpg.<br>        }<br><br>        $io-&gt;info(&quot;Processing file: {$file}&quot;);<br>        $io-&gt;info(&quot;Destination: {$dest}&quot;);<br>        $io-&gt;info(&quot;Generating &quot; . self::TILE_COLS . &quot; columns × &quot; . self::TILE_ROWS . &quot; rows&quot;);<br>        $io-&gt;info(&quot;Output format: {$extension}&quot;);<br><br>        // Generate tiles using ImageMagick.<br>        $tileName = $dest . &#39;/&#39; . self::TILE_PATTERN . &#39;.&#39; . $extension;<br>        $cropPattern = sprintf(&#39;%dx%d@&#39;, self::TILE_COLS, self::TILE_ROWS);<br><br>        $process = new Process([<br>            &#39;convert&#39;,<br>            $file,<br>            &#39;+repage&#39;,<br>            &#39;-crop&#39;,<br>            $cropPattern,<br>            &#39;+repage&#39;,<br>            $tileName,<br>        ]);<br><br>        $process-&gt;setTimeout(300); // 5 minutes timeout for large images.<br>        $process-&gt;run();<br><br>        if (!$process-&gt;isSuccessful()) {<br>            $io-&gt;error(&#39;Tile generation failed: &#39; . $process-&gt;getErrorOutput());<br><br>            return Command::FAILURE;<br>        }<br><br>        // Count generated tiles.<br>        $generatedTiles = glob($dest . &#39;/tile_*.&#39; . $extension);<br>        $expectedTiles = self::TILE_COLS * self::TILE_ROWS;<br>        $actualTiles = is_array($generatedTiles) ? count($generatedTiles) : 0;<br><br>        $io-&gt;success(&quot;Tiles generation completed!&quot;);<br>        $io-&gt;info(&quot;Generated {$actualTiles}/{$expectedTiles} tiles&quot;);<br><br>        if ($actualTiles !== $expectedTiles) {<br>            $io-&gt;warning(&quot;Expected {$expectedTiles} tiles but generated {$actualTiles}&quot;);<br>        }<br><br>        return Command::SUCCESS;<br>    }<br><br>    /**<br>     * Check if ImageMagick is installed and available on the system.<br>     */<br>    private function isImageMagickAvailable(): bool<br>    {<br>        $process = new Process([&#39;convert&#39;, &#39;-version&#39;]);<br>        $process-&gt;run();<br><br>        return $process-&gt;isSuccessful();<br>    }<br><br>    /**<br>     * Check if destination directory already contains tile files.<br>     */<br>    private function destinationHasTiles(string $destination): bool<br>    {<br>        if (!is_dir($destination)) {<br>            return false;<br>        }<br><br>        // Check for common image extensions.<br>        $patterns = [<br>            $destination . &#39;/tile_*.jpg&#39;,<br>            $destination . &#39;/tile_*.jpeg&#39;,<br>            $destination . &#39;/tile_*.png&#39;,<br>            $destination . &#39;/tile_*.webp&#39;,<br>            $destination . &#39;/tile_*.avif&#39;,<br>        ];<br><br>        foreach ($patterns as $pattern) {<br>            $files = glob($pattern);<br>            if (is_array($files) &amp;&amp; count($files) &gt; 0) {<br>                return true;<br>            }<br>        }<br><br>        return false;<br>    }<br>}</pre><p><strong>Technical Prerequisites</strong></p><ul><li><strong>ImageMagick</strong>: convertcommand</li></ul><h4>Usage Examples</h4><pre># Basic usage - process an image and chunnk it into tiles<br>php bin/console app:image:tiler -f /path/to/panoramas -dest ./dest/to/tilesphp bin/console app:image:tiler --file=PATH --destination=PATH</pre><p>Required Options</p><ul><li>--file or -f: Image files.</li><li>--destination or -dest: Tiles destination.</li></ul><h3>The Magic</h3><p>The core of this command lies in a single, elegant ImageMagick command:</p><pre>convert image.jpg +repage -crop 16x8@ +repage tile_%03d.jpgb</pre><p>Let me break this down:</p><ul><li><strong>+repage</strong>: Resets the virtual canvas — essential when working with crops to avoid offset issues</li><li><strong>-crop 16x8@</strong>: The @ suffix is the magic here. It tells ImageMagick to divide the image into a grid of 16 columns by 8 rows, automatically calculating tile dimensions</li><li><strong>tile_%03d.jpg</strong>: Output pattern with zero-padded numbering (tile_000, tile_001, etc.)</li></ul><p>This single command handles all the complexity: calculating tile sizes, maintaining aspect ratios, and generating consistently named output files.</p><h3>Real-World Impact</h3><p>On <strong>Respawwwn</strong>, implementing tiling transformed the user experience:</p><ul><li><strong>Initial load time</strong>: Dropped from 4–6 seconds to under 1 second</li><li><strong>Data transferred on first view</strong>: Reduced by approximately 80%</li><li><strong>Mobile experience</strong>: Finally playable on slow 3G connections</li><li><strong>Server bandwidth</strong>: Significantly reduced especially for users who don’t move the panorama view a</li></ul><p>❤️ Love on your keyboards.</p><h4>Sources</h4><p><strong>Photo Sphere Viewer Documentation</strong> (2026) — Equirectangular Tiles Adapter. <br><a href="https://photo-sphere-viewer.js.org/guide/adapters/equirectangular-tiles.html">https://photo-sphere-viewer.js.org/guide/adapters/equirectangular-tiles.html</a></p><p><strong>Simula Research Laboratory &amp; University of Oslo</strong> (May 2015) — Tiling of Panorama Video for Interactive Virtual<br>Cameras: Overheads and Potential Bandwidth Requirement Reduction.<br><a href="https://web-backend.simula.no/sites/default/files/publications/files/pv2015.compressed.pdf">https://web-backend.simula.no/sites/default/files/publications/files/pv2015.compressed.pdf</a></p><h4>Resources</h4><p><strong>Respawwwn, </strong><a href="https://respawwwn.com/">https://respawwwn.com</a><br>Daily video game quiz &amp; case study of this article.</p><p><strong>Claude AI, </strong><a href="https://claude.ai/">https://claude.ai</a><br>Helped with writing and text refinement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9d34fa9832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP 8.4 Features I can’t live without anymore]]></title>
            <link>https://wengerk.medium.com/php-8-4-features-i-cant-live-without-anymore-b35cbe05d55f?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35cbe05d55f</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 08:02:44 GMT</pubDate>
            <atom:updated>2026-01-05T08:02:44.710Z</atom:updated>
            <content:encoded><![CDATA[<p>PHP 8.4 was released on <em>November 21, 2024</em>. Today is… well, let’s just say it’s been a while.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yW7YrCAoXjrOKJ1i53P_PQ.png" /><figcaption>Sneak peek of PHP 8.4’s QOL upgrades, brought to life by Nano Banana 🐘</figcaption></figure><p>As we say in French: <em>mieux vaut tard que jamais</em> — better late than never. And let’s be honest, when you’re juggling production projects, client deadlines, and that one legacy codebase that refuses to die, upgrading PHP isn’t always day-one priority.</p><p>But here we are! And I’m genuinely excited to share these features with you — even if half of you have probably been using them in production for months. No judgment from me. Okay, maybe a little judgment towards myself.</p><p><em>Not a Medium member yet? </em><a href="https://medium.com/@wengerk/php-8-4-features-i-cant-live-without-anymore-b35cbe05d55f"><em>Click here to access this article for free</em></a><em>!</em></p><h3>🪝<strong>Property Hooks — The Game Changer</strong></h3><p>Property hooks might be the biggest quality-of-life improvement since constructor property promotion. I’m not being dramatic — this genuinely changes how I write classes.</p><p>No more boilerplate getters. No more repetitive setters. You define the logic directly on the property itself.</p><p>Before PHP 8.4, a simple class with getters &amp; seters looked like this:</p><pre>class Player {<br>    private string $email;<br>    private string $firstName;<br>    private string $lastName;<br><br>    public function getEmail(): string {<br>        return $this-&gt;email;<br>    }<br><br>    public function setEmail(string $email): void {<br>        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {<br>            throw new InvalidArgumentException(&#39;Invalid email format&#39;);<br>        }<br>        $this-&gt;email = $email;<br>    }<br><br>    public function getFirstName(): string {<br>        return $this-&gt;firstName;<br>    }<br><br>    public function setFirstName(string $firstName): void {<br>        if (empty(trim($firstName))) {<br>            throw new InvalidArgumentException(&#39;First name cannot be empty&#39;);<br>        }<br>        $this-&gt;firstName = trim($firstName);<br>    }<br><br>    public function getLastName(): string {<br>        return $this-&gt;lastName;<br>    }<br><br>    public function setLastName(string $lastName): void {<br>        if (empty(trim($lastName))) {<br>            throw new InvalidArgumentException(&#39;Last name cannot be empty&#39;);<br>        }<br>        $this-&gt;lastName = trim($lastName);<br>    }<br><br>    public function getFullName(): string {<br>        return $this-&gt;firstName . &#39; &#39; . $this-&gt;lastName;<br>    }<br>}</pre><p>As of PHP 8.4, all of that boilerplate can be reduced to this:</p><pre>class Player {<br>    public string $email {<br>        set {<br>            if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {<br>                throw new InvalidArgumentException(&#39;Invalid email format&#39;);<br>            }<br>            $this-&gt;email = $value;<br>        }<br>    }<br><br>    public string $firstName {<br>        set =&gt; trim($value) ?: throw new InvalidArgumentException(&#39;First name cannot be empty&#39;);<br>    }<br><br>    public string $lastName {<br>        set =&gt; trim($value) ?: throw new InvalidArgumentException(&#39;Last name cannot be empty&#39;);<br>    }<br><br>    public string $fullName {<br>        get =&gt; $this-&gt;firstName . &#39; &#39; . $this-&gt;lastName;<br>    }<br>}</pre><p>Here’s the cool part: $fullName is a virtual property. It doesn&#39;t actually store data — it&#39;s computed on-the-fly from firstName and lastName. No wasted memory, no sync issues.</p><p>I could keep going, but others have already explored this better than I could. For the full deep-dive — asymmetric visibility, edge cases &amp; advanced usage — check out these two excellent articles: <a href="https://phpfashion.com/en/property-hooks-in-php-8-4">Property Hooks in PHP 8.4: Game Changer or Hidden Trap?</a> &amp; <a href="https://fsck.sh/en/blog/php-84-property-hooks-guide/">PHP 8.4 Property Hooks: The Game-Changer You’ve Been Waiting For</a>.</p><h3>🆕 new without Parentheses — Goodbye Brackets</h3><p>PHP 8.4 brings another small-but-mighty improvement: you don’t have to wrap new invocations in parentheses anymore to chain methods.</p><p>Instead of this gymnastics:</p><pre>$name = (new MyClass())-&gt;myMethod();</pre><p>You can now simply write:</p><pre>$name = new MyClass()-&gt;myMethod();</pre><p>This might seem like a small change, but small improvements to developer experience compound over time. Your future self will thank you.</p><h3>🏁 <strong>The </strong>#[Deprecated]<strong> Attribute — Finally, Native Support</strong></h3><p>Remember the good old /** @deprecated */ docblock? Sure, <em>PHPStorm</em> understood it, and static analysers like <em>PHPStan</em> could catch it — but PHP itself? It couldn&#39;t care less. You were basically leaving a polite note that the language completely ignored.</p><p>Well, not anymore. PHP 8.4 introduces a native #[Deprecated] attribute that the engine actually respects. And the cherry on top? It enforces metadata to explain <em>what</em> to use instead and <em>since when</em> it&#39;s deprecated:</p><pre>#[Deprecated(<br>    message: &quot;use writeArticleOnTime() instead&quot;,<br>    since: &quot;kevin/procrastination:13.0&quot;<br>)]<br>function writeArticleAboutPHP84(): void<br>{<br>    // I&#39;ll do it next week, I promise<br>}</pre><p>PHP 8.4 might be old news by now, but these features are here to stay. Property hooks, cleaner instantiation, native deprecations — small wins that make daily coding just a bit more enjoyable.</p><p>Now if you’ll excuse me, I have a PHP 8.5 article to procrastinate on.</p><p>❤️ Love on your keyboards.</p><h3>Sources</h3><p><strong>stitcher.io </strong>(Nov 2024) What’s new in PHP 8.4.<br><a href="https://stitcher.io/blog/new-in-php-84">https://stitcher.io/blog/new-in-php-84</a></p><p><strong>David Grudl (</strong>Nov 2024<strong>). </strong>Property Hooks in PHP 8.4: Game Changer or Hidden Trap?<br><a href="https://phpfashion.com/en/property-hooks-in-php-8-4">https://phpfashion.com/en/property-hooks-in-php-8-4</a></p><p><strong>Matthias Breddin (</strong>Nov 2025<strong>). </strong>PHP 8.4 Property Hooks: The Game-Changer You’ve Been Waiting For.<br><a href="https://fsck.sh/en/blog/php-84-property-hooks-guide/">https://fsck.sh/en/blog/php-84-property-hooks-guide</a></p><p><strong>PHP RFC</strong> (Dec 2022) Property hooks.<br><a href="https://wiki.php.net/rfc/property-hooks">https://wiki.php.net/rfc/property-hooks</a></p><p><strong>PHP RFC</strong> (Dec 2023) new MyClass()-&gt;method() without parentheses.<br><a href="https://wiki.php.net/rfc/new_without_parentheses">https://wiki.php.net/rfc/new_without_parentheses</a></p><p><strong>PHP RFC</strong> (May 2024) #[\Deprecated] Attribute.<br><a href="https://wiki.php.net/rfc/deprecated_attribute">https://wiki.php.net/rfc/deprecated_attribute</a></p><h3>Resources</h3><p><strong>Claude AI, </strong><a href="https://claude.ai/">https://claude.ai</a><br>Helped with writing and text refinement.</p><p><strong>Nano Banana, </strong><a href="https://gemini.google/overview/image-generation/">https://gemini.google/overview/image-generation</a><br>Generated the very accurate article’s cover illustration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35cbe05d55f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Watermarks to Images with Symfony, ImageMagick & ExifTool]]></title>
            <link>https://wengerk.medium.com/how-to-add-watermarks-to-images-with-symfony-imagemagick-exiftool-dc640a7ee22e?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc640a7ee22e</guid>
            <category><![CDATA[watermark]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[exiftool]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[imagemagick]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 07:02:45 GMT</pubDate>
            <atom:updated>2025-12-18T07:02:45.143Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had to create a solution to automate watermark addition on images for my side-project <strong>Respawwn</strong>. For those who don’t know <a href="https://respawwwn.com/">Respawwn</a> (yet), it’s a daily video-game quiz that tests your video game expertise with game screenshots to guess. A real challenge for gaming enthusiasts! 👾</p><blockquote>Watermarking is not an effective protection method !</blockquote><h3>Protecting Our Creations Against Theft</h3><p>In my work on Respawwn, I regularly create screenshots for quizzes. Unfortunately, some people don’t hesitate to steal my creations for their own profit. Faced with this reality, I had to implement an automated watermarking system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38dsPRw7RrFFnTlBRoFPvA.jpeg" /><figcaption>Illustration process of Watermark</figcaption></figure><p>I need to be honest with you: <strong>watermarking is not an effective protection method</strong>. It’s probably one of the worst protection methods that exists. Watermarks can be easily removed or bypassed using image editing software or AI. Furthermore, they can detract from the visual appeal of an image and are not effective at preventing theft if someone is determined to reproduce or distribute the image.<br>Even though some watermarks can be relatively easy to remove with readily available tools, they can still act as a deterrent and make it more difficult for someone to easily use and pass off your work as their own.</p><h3>Before Starting: Create Your Watermark</h3><p>The command I’m going to present uses a ready-to-use transparent background watermark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*NnaZjAYSyBFsVrZlu7fwuA.png" /><figcaption>Respawwwn Watermark</figcaption></figure><p>This watermark will be placed in the bottom-right corner of our images and transformed to be 25% of the width of the original image and 30% transparent.</p><h3>Automating the Process</h3><p>Let’s see each process that needs to be present in our <strong>Symfony</strong> command that automates the entire process:</p><h4>Step 1: Resize the Watermark</h4><p>The first step is to obtain the final watermark width and transparency.</p><pre>identify -format &#39;%w %h&#39; /path/to/original-image.jpg</pre><p>For an example image of 1200x600 pixels, the watermark needs to be 300 pixels wide and 30% translucent:</p><pre>convert watermark.png -resize 300x -alpha set -channel A -evaluate multiply 0.3 +channel watermark-resized-transparent.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3Aowcfd8ngmXwzPxqd8lLQ.png" /><figcaption>Our translucent watermark resized to 25% of our original image</figcaption></figure><h4>Step 2: Overlay the Watermark</h4><p>All that’s left is to overlay the watermark on the bottom-right corner.</p><pre>composite -gravity southeast -geometry +10+10 watermark-resized-transparent.png /path/to/original-image.jpg /destination/of/image-with-watermark.jpg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V3cZsf6lbffUKacjujvnA.jpeg" /><figcaption>The Respawwn watermark has been placed on the bottom-right corner</figcaption></figure><p>What’s great about this approach is that it retains all metadata between the source and final image.</p><h3>The Command</h3><p>This Command will apply the Watermark on all images inside a specific directory.</p><pre>&lt;?php<br><br>namespace App\Command;<br><br>use Symfony\Component\Console\Attribute\AsCommand;<br>use Symfony\Component\Console\Command\Command;<br>use Symfony\Component\Console\Input\InputInterface;<br>use Symfony\Component\Console\Input\InputOption;<br>use Symfony\Component\Console\Output\OutputInterface;<br>use Symfony\Component\Console\Style\SymfonyStyle;<br>use Symfony\Component\Finder\Finder;<br>use Symfony\Component\Process\Process;<br><br>#[AsCommand(<br>    name: &#39;app:image:watermark&#39;,<br>    description: &#39;Add watermark to images using ImageMagick.&#39;,<br>)]<br>class ImageWatermarkCommand extends Command<br>{<br>    private const SUPPORTED_FORMATS = [&#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;, &#39;webp&#39;, &#39;avif&#39;];<br>    private const WATERMARK_EXIF_KEY = &#39;Copyright&#39;;<br>    private const WATERMARK_EXIF_VALUE = &#39;Watermark added by Respawwwn&#39;;<br><br>    protected function configure(): void<br>    {<br>        $this<br>            -&gt;addOption(<br>                &#39;directory&#39;,<br>                &#39;d&#39;,<br>                InputOption::VALUE_REQUIRED,<br>                &#39;Directory containing images to process.&#39;<br>            )<br>            -&gt;addOption(<br>                &#39;watermark&#39;,<br>                &#39;w&#39;,<br>                InputOption::VALUE_REQUIRED,<br>                &#39;Path to watermark image file.&#39;<br>            )<br>            -&gt;addOption(<br>                &#39;force&#39;,<br>                &#39;f&#39;,<br>                InputOption::VALUE_NONE,<br>                &#39;Force adding watermark even if already present.&#39;<br>            )<br>    }<br><br>    protected function execute(InputInterface $input, OutputInterface $output): int<br>    {<br>        $io = new SymfonyStyle($input, $output);<br>        $io-&gt;title(&#39;Images Watermark Processing&#39;);<br><br>        $directory = $input-&gt;getOption(&#39;directory&#39;);<br>        $watermarkPath = $input-&gt;getOption(&#39;watermark&#39;);<br>        $force = $input-&gt;getOption(&#39;force&#39;);<br><br>        // Validate inputs.<br>        if (null === $directory || !is_dir($directory)) {<br>            $io-&gt;error(&#39;Directory not found or not specified. Use --directory option.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        if (null === $watermarkPath || !file_exists($watermarkPath)) {<br>            $io-&gt;error(&#39;Watermark file not found or not specified. Use --watermark option.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        // Check if ImageMagick is available.<br>        if (!$this-&gt;isImageMagickAvailable()) {<br>            $io-&gt;error(&#39;ImageMagick is not available. Please install ImageMagick.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        // Check if exiftool is available.<br>        if (!$this-&gt;isExiftoolAvailable()) {<br>            $io-&gt;error(&#39;ExifTool is not available. Please install ExifTool for EXIF manipulation.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        if ($force) {<br>            $io-&gt;info(&#39;Force option is enabled. Watermark will be added to all mages.&#39;);<br>        }<br><br>        $io-&gt;info(&quot;Processing directory: {$directory}&quot;);<br>        $io-&gt;info(&quot;Using watermark: {$watermarkPath}&quot;);<br><br>        // Find all supported image files to process.<br>        $finder = new Finder();<br>        $finder-&gt;files()<br>            -&gt;in($directory)<br>            -&gt;name(&#39;/\.(&#39;.implode(&#39;|&#39;, self::SUPPORTED_FORMATS).&#39;)$/i&#39;);<br><br>        $images = iterator_to_array($finder);<br>        $totalImages = count($images);<br><br>        if (0 === $totalImages) {<br>            $io-&gt;warning(&#39;No supported image files found in the specified directory.&#39;);<br><br>            return Command::SUCCESS;<br>        }<br><br>        $io-&gt;info(&quot;Found {$totalImages} total images.&quot;);<br>        $io-&gt;progressStart($totalImages);<br><br>        $processedCount = 0;<br>        $skippedCount = 0;<br>        $errorCount = 0;<br><br>        foreach ($images as $imageFile) {<br>            $imagePath = $imageFile-&gt;getPathname();<br><br>            try {<br>                // Check if watermark already exists (unless force is enabled).<br>                if (!$force &amp;&amp; $this-&gt;hasWatermark($imagePath)) {<br>                    ++$skippedCount;<br>                    $io-&gt;progressAdvance();<br>                    continue;<br>                }<br><br>                // Process the image.<br>                if ($this-&gt;processImage($imagePath, $watermarkPath, $nadirSize, $io)) {<br>                    ++$processedCount;<br>                } else {<br>                    ++$errorCount;<br>                }<br>            } catch (\Exception $e) {<br>                $io-&gt;error(&quot;Error processing {$imagePath}: &quot;.$e-&gt;getMessage());<br>                ++$errorCount;<br>            }<br><br>            $io-&gt;progressAdvance();<br>        }<br><br>        $io-&gt;progressFinish();<br><br>        $io-&gt;success(&#39;Processing completed!&#39;);<br>        $io-&gt;info(&quot;Total images: {$totalImages}&quot;);<br>        $io-&gt;info(&quot;Processed: {$processedCount}&quot;);<br>        $io-&gt;info(&quot;Skipped (already watermarked): {$skippedCount}&quot;);<br>        $io-&gt;info(&quot;Errors: {$errorCount}&quot;);<br><br>        return Command::SUCCESS;<br>    }<br><br>    /**<br>     * Check if ImageMagick is installed and available on the system.<br>     */<br>    private function isImageMagickAvailable(): bool<br>    {<br>        $process = new Process([&#39;convert&#39;, &#39;-version&#39;]);<br>        $process-&gt;run();<br><br>        return $process-&gt;isSuccessful();<br>    }<br><br>    /**<br>     * Check if ExifTool is installed and available on the system.<br>     */<br>    private function isExiftoolAvailable(): bool<br>    {<br>        $process = new Process([&#39;exiftool&#39;, &#39;-ver&#39;]);<br>        $process-&gt;run();<br><br>        return $process-&gt;isSuccessful();<br>    }<br><br>    /**<br>     * Check if an image already has a watermark.<br>     */<br>    private function hasWatermark(string $imagePath): bool<br>    {<br>        $process = new Process([&#39;exiftool&#39;, &#39;-&#39;.self::WATERMARK_EXIF_KEY, &#39;-s3&#39;, $imagePath]);<br>        $process-&gt;run();<br><br>        if (!$process-&gt;isSuccessful()) {<br>            return false;<br>        }<br><br>        $output = trim($process-&gt;getOutput());<br><br>        return self::WATERMARK_EXIF_VALUE === $output;<br>    }<br><br>    /**<br>     * Process a single image by adding a watermark.<br>     */<br>    private function processImage(string $imagePath, string $watermarkPath, int $nadirSize, SymfonyStyle $io): bool<br>    {<br>        $tempDir = sys_get_temp_dir();<br>        $basename = pathinfo($imagePath, PATHINFO_FILENAME);<br>        $extension = pathinfo($imagePath, PATHINFO_EXTENSION);<br><br>        // Create temporary files for processing<br>        $tempFiles = [<br>            &#39;watermark_resized&#39; =&gt; $tempDir.&#39;/&#39;.$basename.&#39;_watermark_resized.&#39;.pathinfo($watermarkPath, PATHINFO_EXTENSION),<br>            &#39;output&#39; =&gt; $tempDir.&#39;/&#39;.$basename.&#39;_watermarked.&#39;.$extension,<br>        ];<br><br>        try {<br>            // Get image dimensions.<br>            $dimensions = $this-&gt;getImageDimensions($imagePath);<br><br>            if (null === $dimensions || [] === $dimensions) {<br>                $io-&gt;error(&quot;Could not get dimensions for {$imagePath}&quot;);<br><br>                return false;<br>            }<br><br>            [$width] = $dimensions;<br><br>            // Step 1: Resize the Watermark to be 0.25 of image width and make it 30% opaque.<br>            $process = new Process([<br>                &#39;convert&#39;,<br>                $watermarkPath,<br>                &#39;-resize&#39;, intval($width * 0.25).&#39;x&#39;,<br>                &#39;-alpha&#39;, &#39;set&#39;,<br>                &#39;-channel&#39;, &#39;A&#39;,<br>                &#39;-evaluate&#39;, &#39;multiply&#39;, &#39;0.3&#39;,<br>                &#39;+channel&#39;,<br>                $tempFiles[&#39;watermark_resized&#39;],<br>            ]);<br>            $process-&gt;run();<br>            if (!$process-&gt;isSuccessful()) {<br>                throw new \Exception(&#39;Failed to resize watermark to image width: &#39;.$process-&gt;getErrorOutput());<br>            }<br><br>            // Step 2: Apply the Watermark and make a clone output.<br>            $process = new Process([<br>                &#39;composite&#39;,<br>                &#39;-gravity&#39;, &#39;southeast&#39;,<br>                &#39;-geometry&#39;, &#39;+10+10&#39;,<br>                $tempFiles[&#39;watermark_resized&#39;],<br>                $imagePath,<br>                $tempFiles[&#39;output&#39;],<br>            ]);<br><br>            $process-&gt;run();<br>            if (!$process-&gt;isSuccessful()) {<br>                throw new \Exception(&#39;Failed to apply watermark to image width: &#39;.$process-&gt;getErrorOutput());<br>            }<br><br>            // Move the watermarked image to the original filename.<br>            if (!rename($tempFiles[&#39;output&#39;], $imagePath)) {<br>                throw new \Exception(&quot;Failed to create watermarked image at {$imagePath}&quot;);<br>            }<br><br>            // Update EXIF to mark as watermarked.<br>            $this-&gt;updateExifWatermarkFlag($imagePath);<br><br>            return true;<br>        } catch (\Exception $e) {<br>            $io-&gt;error(&quot;Error processing {$imagePath}: &quot;.$e-&gt;getMessage());<br><br>            return false;<br>        } finally {<br>            // Clean up temporary files.<br>            foreach ($tempFiles as $tempFile) {<br>                if (file_exists($tempFile)) {<br>                    unlink($tempFile);<br>                }<br>            }<br>        }<br>    }<br><br>    /**<br>     * Get the dimensions (width and height) of an image.<br>     *<br>     * Uses the identify tool to extract image metadata w/o loading the image.<br>     */<br>    private function getImageDimensions(string $imagePath): ?array<br>    {<br>        $process = new Process([&#39;identify&#39;, &#39;-format&#39;, &#39;%w %h&#39;, $imagePath]);<br>        $process-&gt;run();<br><br>        if (!$process-&gt;isSuccessful()) {<br>            return null;<br>        }<br><br>        $output = trim($process-&gt;getOutput());<br>        $dimensions = explode(&#39; &#39;, $output);<br><br>        if (2 !== count($dimensions)) {<br>            return null;<br>        }<br><br>        return [(int) $dimensions[0], (int) $dimensions[1]];<br>    }<br><br>    /**<br>     * Update the EXIF Copyright field to mark an image as watermarked.<br>     */<br>    private function updateExifWatermarkFlag(string $imagePath): bool<br>    {<br>        $process = new Process([<br>            &#39;exiftool&#39;,<br>            &#39;-&#39;.self::WATERMARK_EXIF_KEY.&#39;=&#39;.self::WATERMARK_EXIF_VALUE,<br>            &#39;-overwrite_original&#39;,<br>            $imagePath,<br>        ]);<br>        $process-&gt;run();<br><br>        return $process-&gt;isSuccessful();<br>    }<br>}</pre><p>Technical Prerequisites</p><ul><li><strong>ImageMagick</strong>: convert, composite, identify commands</li><li><strong>ExifTool</strong>: for EXIF metadata manipulation</li></ul><h4>Using the Command</h4><pre>php bin/console app:image:watermark --directory=PATH --watermark=PATH [options]</pre><p><strong>Required Options</strong></p><ul><li>--directory or -d: Directory containing panoramic images to process.</li><li>--watermark or -w: Path to watermark image file (must be in equirectangular format).</li></ul><p><strong>Optional Parameters</strong></p><ul><li>--force or -f: Force adding watermark even if already present.</li></ul><h4>Usage Examples</h4><pre># Basic usage - process all images in a directory<br>php bin/console app:image:watermark -d /path/to/images -w ./assets/images/watermark.png</pre><pre>php bin/console app:image:watermark -d /path/to/images -w ./assets/images/watermark.png</pre><pre># Force processing all images (ignores existing watermarks)<br>php bin/console app:image:watermark -d /path/to/images -w ./assets/images/watermark.png --force</pre><p>❤️ Love on your keyboards.</p><h3>Sources</h3><p><strong>Lauren Short</strong> (August 2019) Why You Shouldn’t Add a Watermark to Your Photos.<br><a href="https://foodphotographyacademy.co/blog/business/business-why-you-shouldnt-add-a-watermark-to-your-photos/">https://foodphotographyacademy.co/blog/business/business-why-you-shouldnt-add-a-watermark-to-your-photos</a></p><h3>Resources</h3><p><strong>Respawwwn, </strong><a href="https://respawwwn.com/">https://respawwwn.com</a><br>Daily video game quiz &amp; case study of this article.</p><p><strong>Claude AI, </strong><a href="https://claude.ai/">https://claude.ai</a><br>Helped with writing and text refinement.</p><p><strong>Imagen, </strong><a href="https://deepmind.google/models/imagen/">https://deepmind.google/models/imagen/</a><br>Generated the very accurate article’s cover illustration.</p><p>Cet article a d’abord été rédigé pour le blog d’Antistatique — Agence Web à Lausanne, Suisse. Un endroit où je travaille en tant que Senior Backend Developer. N’hésitez pas à le lire ici ou à aller le consulter là-bas : <a href="https://antistatique.net/en/blog">https://antistatique.net/en/blog</a></p><p>Toutes les images sont la propriété de leurs auteurs respectifs. Un grand merci à @Antistatique pour la relecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc640a7ee22e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Watermarks to 360° Panoramas with Symfony, ImageMagick & ExifTool]]></title>
            <link>https://wengerk.medium.com/how-to-add-watermarks-to-360-panoramas-with-symfony-imagemagick-exiftool-7348b7b39906?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7348b7b39906</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[exiftool]]></category>
            <category><![CDATA[imagemagick]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[watermark]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 07:02:37 GMT</pubDate>
            <atom:updated>2025-12-27T13:06:53.612Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had to create a solution to automate watermark addition on 360° panoramic images for my side-project <strong>Respawwwn</strong>. For those who don’t know <a href="https://respawwwn.com/">Respawwwn</a> yet, it’s a daily video-game quiz that tests your video game expertise with game Panorama to guess. A real challenge for gaming enthusiasts ! 👾</p><blockquote><strong>Watermarking is not an effective protection method !</strong></blockquote><h3>Protecting Our Creations Against Theft</h3><p>In my work on Respawwwn, I regularly create custom 360° panoramas for quizzes. Unfortunately, some people don’t hesitate to steal my creations for their own profit. Faced with this reality, I had to implement an automated watermarking system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TcaDCM7xnMCrJE5l9K0TzA.jpeg" /><figcaption>Illustration process of Nadir’s generation pipeline</figcaption></figure><p>I need to be honest with you: <strong>watermarking is not an effective protection method</strong>. It’s probably one of the worst protection methods that exists. Watermarks can be easily removed or bypassed using image editing software or AI. Furthermore, they can detract from the visual appeal of an image and are not effective at preventing theft if someone is determined to reproduce or distribute the image.<br>Even though some watermarks can be relatively easy to remove with readily available tools, they can still act as a deterrent and make it more difficult for someone to easily use and pass off your work as their own.</p><h3>Before Starting: Create Your Equirectangular Watermark</h3><p>The command I’m going to present uses a watermark already converted to equirectangular projection.</p><p>But here’s the thing: you can’t just slap any regular logo onto a 360° panorama and expect it to look right. We need to create what’s called a <strong>nadir watermark</strong>.</p><p>The <strong>nadir</strong> is the point directly below the observer in a 360° panorama — essentially the “floor” of your spherical image. When you look down in a 360° viewer, you’re looking at the nadir. This is the perfect spot for watermarks because it’s naturally where viewers expect to see branding or logos, and it doesn’t interfere with the main panoramic content.</p><blockquote>We need multiple transformation steps to create a proper nadir watermark that will appear correctly when viewed in 360. Aregular flat logo would appear severely distorted when placed at the nadir. Think of it like trying to wrap a flat sticker around a basketball — it just doesn’t work properly without some mathematical magic.</blockquote><p><strong>1. Create a 500x500 Flat Watermark<br></strong>Start by creating your logo or watermark in a square format of 500x500 pixels. This will be your working base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ypVvararUeNpqBhTnHm0CQ.png" /><figcaption>Respawwwn original watermark 500x500</figcaption></figure><p><strong>2. Convert the Logo to Equirectangular Projection</strong><br>For a watermark to display correctly on a 360° panoramic image, it must be transformed according to equirectangular projection. Here’s how to proceed with ImageMagick.</p><p>3.Rotate 180 Degrees<br>Why this step? This initial rotation prepares the image for the polar transformation. The DePolar distortion expects the image to be oriented in a specific way, and this rotation ensures the final result will be properly oriented when applied to the nadir.</p><pre>convert watermark.png -rotate 180 watermark-1.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*EL3bdOaomrCmgWKWbnuoyA.png" /><figcaption>Rotated -180° of the original Watermark</figcaption></figure><p>4. <strong>DePolar Distortion<br></strong>This step uses ImageMagick’s DePolar transformation to convert the image to polar projection.</p><pre>convert watermark-1.png -distort DePolar 0 watermark-2.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ymMpZO_vowIJ2iOn1OwAvw.png" /><figcaption>Distored version of our previously rotated Watermark</figcaption></figure><p><strong>5.Flip Vertically<br></strong>After the polar transformation, the image orientation needs to be corrected for the specific way 360° panoramas are structured. This vertical flip ensures that when the watermark is applied to the nadir, it will appear right-side-up to viewers looking down.</p><pre>convert watermark-2.png -flip watermark-3.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cPu8X-MBniJ7m9VSmsN0RQ.png" /><figcaption>Flipped version of our Distorded Watermark</figcaption></figure><p><strong>6. Flop Horizontally<br></strong>This final horizontal flip completes the orientation correction. Combined with the previous transformations, this ensures that text and directional elements in your logo will appear correctly oriented when viewed in the 360° environment.</p><pre>convert watermark-3.png -flop watermark-final.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1tlzl1U8m3WwlXtGRCQhmA.png" /><figcaption>Our final equirectangle Watermark ready for Action ❤️‍🔥</figcaption></figure><p>Perfect! Your watermark is now ready to be used on 360° panoramas.</p><h3>Automating the Process</h3><p>Let’s see each process that needs to be present in our <strong>Symfony</strong> command that automates the entire process:</p><h4>Step 1: Resize the Nadir</h4><p>The first step is to obtain the image resolution (width x height).</p><pre>identify -format &#39;%w %h&#39; /path/to/original-panorama.jpg</pre><p>For an example image of 1200x600 pixels, the nadir needs to be 1200 pixels wide:</p><pre>convert watermark-360.png -geometry 1200x500! watermark-360-nadir.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYosS69U3u9eglLxYYdT-A.png" /><figcaption>Our Nadir Watermark stretched to 1200px</figcaption></figure><p>Next, we need to reduce the nadir size. Generally, a nadir covers 10% to 20% of the photo. Let’s use 20% for this example:</p><pre>600 (photo height) * 0.2 (percentage) = 120</pre><p>We can now resize the nadir to 120 pixels in height:</p><pre>convert watermark-360-nadir.png -geometry 1200x120! watermark-360-nadir.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKhdbOGWbsaPygU2W_n-NA.png" /><figcaption>Resized Watermark to be 20% of our Panorama size</figcaption></figure><h4>Step 2: Overlay the Nadir</h4><p>All that’s left is to overlay the equirectangular nadir onto the photo.</p><p>We need to calculate where to place the nadir vertically. Knowing the photo is 600 pixels in height and the nadir 120 pixels:</p><pre>composite watermark-360-nadir.png /path/to/original-panorama.jpg -geometry +0+480 /destination/of/panorama-with-watermark.jpg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6O-FbJBl82gQZdpqmtTa9g.jpeg" /></figure><p>What’s great about this approach is that it retains all metadata between the source and final image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7mZX6mJIv7rGeaHXqhhLuQ.gif" /></figure><h3>The Command</h3><p>This Command will apply the Watermark on all panorama images inside a specific directory.</p><pre>&lt;?php<br><br>namespace App\Command;<br><br>use Symfony\Component\Console\Attribute\AsCommand;<br>use Symfony\Component\Console\Command\Command;<br>use Symfony\Component\Console\Input\InputInterface;<br>use Symfony\Component\Console\Input\InputOption;<br>use Symfony\Component\Console\Output\OutputInterface;<br>use Symfony\Component\Console\Style\SymfonyStyle;<br>use Symfony\Component\Finder\Finder;<br>use Symfony\Component\Process\Process;<br><br>#[AsCommand(<br>    name: &#39;app:image:watermark&#39;,<br>    description: &#39;Add watermark to images using ImageMagick.&#39;,<br>)]<br>class PanoramaWatermarkCommand extends Command<br>{<br>    private const SUPPORTED_FORMATS = [&#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;, &#39;webp&#39;, &#39;avif&#39;];<br>    private const WATERMARK_EXIF_KEY = &#39;Copyright&#39;;<br>    private const WATERMARK_EXIF_VALUE = &#39;Watermark added by Respawwwn&#39;;<br><br>    protected function configure(): void<br>    {<br>        $this<br>            -&gt;addOption(<br>                &#39;directory&#39;,<br>                &#39;d&#39;,<br>                InputOption::VALUE_REQUIRED,<br>                &#39;Directory containing images to process.&#39;<br>            )<br>            -&gt;addOption(<br>                &#39;watermark&#39;,<br>                &#39;w&#39;,<br>                InputOption::VALUE_REQUIRED,<br>                &#39;Path to watermark image file.&#39;<br>            )<br>            -&gt;addOption(<br>                &#39;force&#39;,<br>                &#39;f&#39;,<br>                InputOption::VALUE_NONE,<br>                &#39;Force adding watermark even if already present.&#39;<br>            )<br>    }<br><br>    protected function execute(InputInterface $input, OutputInterface $output): int<br>    {<br>        $io = new SymfonyStyle($input, $output);<br>        $io-&gt;title(&#39;Images Watermark Processing&#39;);<br><br>        $directory = $input-&gt;getOption(&#39;directory&#39;);<br>        $watermarkPath = $input-&gt;getOption(&#39;watermark&#39;);<br>        $force = $input-&gt;getOption(&#39;force&#39;);<br><br>        // Validate inputs.<br>        if (null === $directory || !is_dir($directory)) {<br>            $io-&gt;error(&#39;Directory not found or not specified. Use --directory option.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        if (null === $watermarkPath || !file_exists($watermarkPath)) {<br>            $io-&gt;error(&#39;Watermark file not found or not specified. Use --watermark option.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        // Check if ImageMagick is available.<br>        if (!$this-&gt;isImageMagickAvailable()) {<br>            $io-&gt;error(&#39;ImageMagick is not available. Please install ImageMagick.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        // Check if exiftool is available.<br>        if (!$this-&gt;isExiftoolAvailable()) {<br>            $io-&gt;error(&#39;ExifTool is not available. Please install ExifTool for EXIF manipulation.&#39;);<br><br>            return Command::FAILURE;<br>        }<br><br>        if ($force) {<br>            $io-&gt;info(&#39;Force option is enabled. Watermark will be added to all 360 panorama images.&#39;);<br>        }<br><br>        $io-&gt;info(&quot;Processing directory: {$directory}&quot;);<br>        $io-&gt;info(&quot;Using watermark: {$watermarkPath}&quot;);<br><br>        // Find all supported image files to process.<br>        $finder = new Finder();<br>        $finder-&gt;files()<br>            -&gt;in($directory)<br>            -&gt;name(&#39;/\.(&#39;.implode(&#39;|&#39;, self::SUPPORTED_FORMATS).&#39;)$/i&#39;);<br><br>        $images = iterator_to_array($finder);<br>        $totalImages = count($images);<br><br>        if (0 === $totalImages) {<br>            $io-&gt;warning(&#39;No supported image files found in the specified directory.&#39;);<br><br>            return Command::SUCCESS;<br>        }<br><br>        $io-&gt;info(&quot;Found {$totalImages} 360 equirectangular panorama images.&quot;);<br>        $io-&gt;progressStart($totalImages);<br><br>        $processedCount = 0;<br>        $skippedCount = 0;<br>        $errorCount = 0;<br><br>        foreach ($images as $imageFile) {<br>            $imagePath = $imageFile-&gt;getPathname();<br><br>            try {<br>                // Check if watermark already exists (unless force is enabled).<br>                if (!$force &amp;&amp; $this-&gt;hasWatermark($imagePath)) {<br>                    ++$skippedCount;<br>                    $io-&gt;progressAdvance();<br>                    continue;<br>                }<br><br>                // Process the image.<br>                if ($this-&gt;processImage($imagePath, $watermarkPath, $nadirSize, $io)) {<br>                    ++$processedCount;<br>                } else {<br>                    ++$errorCount;<br>                }<br>            } catch (\Exception $e) {<br>                $io-&gt;error(&quot;Error processing {$imagePath}: &quot;.$e-&gt;getMessage());<br>                ++$errorCount;<br>            }<br><br>            $io-&gt;progressAdvance();<br>        }<br><br>        $io-&gt;progressFinish();<br><br>        $io-&gt;success(&#39;Processing completed!&#39;);<br>        $io-&gt;info(&quot;Total 360 panorama images: {$totalImages}&quot;);<br>        $io-&gt;info(&quot;Processed: {$processedCount}&quot;);<br>        $io-&gt;info(&quot;Skipped (already watermarked): {$skippedCount}&quot;);<br>        $io-&gt;info(&quot;Errors: {$errorCount}&quot;);<br><br>        return Command::SUCCESS;<br>    }<br><br>    /**<br>     * Check if ImageMagick is installed and available on the system.<br>     */<br>    private function isImageMagickAvailable(): bool<br>    {<br>        $process = new Process([&#39;convert&#39;, &#39;-version&#39;]);<br>        $process-&gt;run();<br><br>        return $process-&gt;isSuccessful();<br>    }<br><br>    /**<br>     * Check if ExifTool is installed and available on the system.<br>     */<br>    private function isExiftoolAvailable(): bool<br>    {<br>        $process = new Process([&#39;exiftool&#39;, &#39;-ver&#39;]);<br>        $process-&gt;run();<br><br>        return $process-&gt;isSuccessful();<br>    }<br><br>    /**<br>     * Check if an image already has a watermark.<br>     */<br>    private function hasWatermark(string $imagePath): bool<br>    {<br>        $process = new Process([&#39;exiftool&#39;, &#39;-&#39;.self::WATERMARK_EXIF_KEY, &#39;-s3&#39;, $imagePath]);<br>        $process-&gt;run();<br><br>        if (!$process-&gt;isSuccessful()) {<br>            return false;<br>        }<br><br>        $output = trim($process-&gt;getOutput());<br><br>        return self::WATERMARK_EXIF_VALUE === $output;<br>    }<br><br>    /**<br>     * Process a single panorama image by adding a watermark.<br>     */<br>    private function processImage(string $imagePath, string $watermarkPath, int $nadirSize, SymfonyStyle $io): bool<br>    {<br>        $tempDir = sys_get_temp_dir();<br>        $basename = pathinfo($imagePath, PATHINFO_FILENAME);<br>        $extension = pathinfo($imagePath, PATHINFO_EXTENSION);<br><br>        // Create temporary files for processing<br>        $tempFiles = [<br>            &#39;watermark_resized&#39; =&gt; $tempDir.&#39;/&#39;.$basename.&#39;_watermark_resized.&#39;.pathinfo($watermarkPath, PATHINFO_EXTENSION),<br>            &#39;output&#39; =&gt; $tempDir.&#39;/&#39;.$basename.&#39;_watermarked.&#39;.$extension,<br>        ];<br><br>        try {<br>            // Get image dimensions.<br>            $dimensions = $this-&gt;getImageDimensions($imagePath);<br><br>            if (null === $dimensions || [] === $dimensions) {<br>                $io-&gt;error(&quot;Could not get dimensions for {$imagePath}&quot;);<br><br>                return false;<br>            }<br><br>            [$width, $height] = $dimensions;<br><br>            // Step 2: Resize the nadir<br>            // 2.1 Resize to image width.<br>            $process = new Process([&#39;convert&#39;, $watermarkPath, &#39;-geometry&#39;, $width.&#39;x500!&#39;, $tempFiles[&#39;watermark_resized&#39;]]);<br>            $process-&gt;run();<br>            if (!$process-&gt;isSuccessful()) {<br>                throw new \Exception(&#39;Failed to resize watermark to image width: &#39;.$process-&gt;getErrorOutput());<br>            }<br><br>            // 2.2 Calculate nadir height based on percentage.<br>            $nadirHeight = (int) ($height * ($nadirSize / 100));<br><br>            $process = new Process([&#39;convert&#39;, $tempFiles[&#39;watermark_resized&#39;], &#39;-geometry&#39;, $width.&#39;x&#39;.$nadirHeight.&#39;!&#39;, $tempFiles[&#39;watermark_resized&#39;]]);<br>            $process-&gt;run();<br>            if (!$process-&gt;isSuccessful()) {<br>                throw new \Exception(&#39;Failed to resize watermark to final size: &#39;.$process-&gt;getErrorOutput());<br>            }<br><br>            // Step 3: Overlay the nadir.<br>            $verticalOffset = $height - $nadirHeight;<br>            $process = new Process([&#39;composite&#39;, $tempFiles[&#39;watermark_resized&#39;], $imagePath, &#39;-geometry&#39;, &#39;+0+&#39;.$verticalOffset, $tempFiles[&#39;output&#39;]]);<br>            $process-&gt;run();<br>            if (!$process-&gt;isSuccessful()) {<br>                throw new \Exception(&#39;Failed to composite watermark: &#39;.$process-&gt;getErrorOutput());<br>            }<br><br>            // Move the watermarked image to the original filename.<br>            if (!rename($tempFiles[&#39;output&#39;], $imagePath)) {<br>                throw new \Exception(&quot;Failed to create watermarked image at {$imagePath}&quot;);<br>            }<br><br>            // Update EXIF to mark as watermarked.<br>            $this-&gt;updateExifWatermarkFlag($imagePath);<br><br>            return true;<br>        } catch (\Exception $e) {<br>            $io-&gt;error(&quot;Error processing {$imagePath}: &quot;.$e-&gt;getMessage());<br><br>            return false;<br>        } finally {<br>            // Clean up temporary files.<br>            foreach ($tempFiles as $tempFile) {<br>                if (file_exists($tempFile)) {<br>                    unlink($tempFile);<br>                }<br>            }<br>        }<br>    }<br><br>    /**<br>     * Get the dimensions (width and height) of an image.<br>     *<br>     * Uses the identify tool to extract image metadata w/o loading the image.<br>     */<br>    private function getImageDimensions(string $imagePath): ?array<br>    {<br>        $process = new Process([&#39;identify&#39;, &#39;-format&#39;, &#39;%w %h&#39;, $imagePath]);<br>        $process-&gt;run();<br><br>        if (!$process-&gt;isSuccessful()) {<br>            return null;<br>        }<br><br>        $output = trim($process-&gt;getOutput());<br>        $dimensions = explode(&#39; &#39;, $output);<br><br>        if (2 !== count($dimensions)) {<br>            return null;<br>        }<br><br>        return [(int) $dimensions[0], (int) $dimensions[1]];<br>    }<br><br>    /**<br>     * Update the EXIF Copyright field to mark an image as watermarked.<br>     */<br>    private function updateExifWatermarkFlag(string $imagePath): bool<br>    {<br>        $process = new Process([<br>            &#39;exiftool&#39;,<br>            &#39;-&#39;.self::WATERMARK_EXIF_KEY.&#39;=&#39;.self::WATERMARK_EXIF_VALUE,<br>            &#39;-overwrite_original&#39;,<br>            $imagePath,<br>        ]);<br>        $process-&gt;run();<br><br>        return $process-&gt;isSuccessful();<br>    }<br>}</pre><p>Technical Prerequisites</p><ul><li><strong>ImageMagick</strong>: convert, composite, identify commands</li><li><strong>ExifTool</strong>: for EXIF metadata manipulation</li></ul><h4>Using the Command</h4><pre>php bin/console app:panorama:watermark --directory=PATH --watermark=PATH [options]</pre><p><strong>Required Options</strong></p><ul><li>--directory or -d: Directory containing panoramic images to process.</li><li>--watermark or -w: Path to watermark image file (must be in equirectangular format).</li></ul><p><strong>Optional Parameters</strong></p><ul><li>--nadir-size=X or -s X: Watermark size as percentage of image height (default: 20%, between 1-50%).</li><li>--force or -f: Force adding watermark even if already present.</li></ul><h4>Usage Examples</h4><pre># Basic usage - process all 360° panoramas in a directory<br>php bin/console app:panorama:watermark -d /path/to/panoramas -w ./assets/images/watermark-360.png<br><br># Custom nadir size (15% of image height)<br>php bin/console app:panorama:watermark -d /path/to/panoramas -w ./assets/images/watermark-360.png -s 15<br><br># Force processing all images (ignores existing watermarks)<br>php bin/console app:panorama:watermark -d /path/to/panoramas -w ./assets/images/watermark-360.png --force</pre><p>❤️ Love on your keyboards.</p><h3>Sources</h3><p><strong>Lauren Short</strong> (August 2019) Why You Shouldn’t Add a Watermark to Your Photos.<br><a href="https://foodphotographyacademy.co/blog/business/business-why-you-shouldnt-add-a-watermark-to-your-photos/">https://foodphotographyacademy.co/blog/business/business-why-you-shouldnt-add-a-watermark-to-your-photos</a></p><p><strong>Trek View </strong>(January 2022) Adding a Custom Watermark to Hero Photo Video.<br><a href="https://www.trekview.org/blog/adding-a-custom-watermark-to-hero-photo-video/">https://www.trekview.org/blog/adding-a-custom-watermark-to-hero-photo-video</a></p><p><strong>Trek View </strong>(October 2021) Adding a Custom Nadir to 360 Video Photo.<br><a href="https://www.trekview.org/blog/adding-a-custom-nadir-to-360-video-photo/">https://www.trekview.org/blog/adding-a-custom-nadir-to-360-video-photo</a></p><h3>Resources</h3><p><strong>Respawwwn, </strong><a href="https://respawwwn.com/">https://respawwwn.com</a><br>Daily video game quiz &amp; case study of this article.</p><p><strong>Claude AI, </strong><a href="https://claude.ai/">https://claude.ai</a><br>Helped with writing and text refinement.</p><p><strong>Imagen, </strong><a href="https://deepmind.google/models/imagen/">https://deepmind.google/models/imagen/</a><br>Generated the very accurate article’s cover illustration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7348b7b39906" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Les dessous du code]]></title>
            <link>https://wengerk.medium.com/les-dessous-du-code-34f1890117cb?source=rss-43dda52695e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/34f1890117cb</guid>
            <category><![CDATA[professional-workarounds]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Kevin Wenger]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 07:07:01 GMT</pubDate>
            <atom:updated>2025-11-01T07:07:01.391Z</atom:updated>
            <content:encoded><![CDATA[<p>On a tous vécu ce moment dans notre métier : 13h, deadline dans 4 heures, et tu regardes ton écran en te disant : “OK, cette solution n’est pas élégante, mais elle marche… Est-ce que je suis une fraude ?”</p><p><strong>La réponse est non. Et je vais te le prouver.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJu200-H5f9vuFfXoY7hbQ.jpeg" /><figcaption>Behind the curtain</figcaption></figure><p>En tant que développeurs, on se met une pression monstre. On dévore des articles sur les design patterns, on suit religieusement des conférences où chaque ligne de code semble sortir d’un poème, on parcourt du code open-source qui respire l’élégance. Et quand notre propre code ressemble moins à un génie d’architecture et plus à une cabane bricolée avec du duct tape, on culpabilise.</p><p>On se dit qu’on n’est pas à la hauteur. Qu’on devrait faire mieux. Que les “vrais” développeurs n’ont pas besoin de ces workarounds douteux.</p><p><strong>Mais voici la vérité que personne n’ose te dire</strong> : Apple, Nintendo, Bethesda et tous les géants que tu admires font des hacks. Des gros. Des très sales même. Et ils shippent quand même des produits que des millions de personnes utilisent chaque jour sans sourciller.</p><h3>The loop is a lie</h3><p>Commençons par un exemple qui m’a fait sourire : l’horloge de l’application Alarme de l’iPhone.</p><p>Tu sais, ce joli sélecteur de temps qui donne l’impression de défiler infiniment à travers les heures et les minutes ? Ce scroll si fluide, si satisfaisant, qui semble boucler à l’infini ?</p><p>Eh bien, ce n’est <strong>pas</strong> une boucle. C’est juste… une très, très longue liste pré-générée d’heures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7sqo49lhBnrSPhR_iQzyLg.gif" /><figcaption>Wait for it …. ⌚</figcaption></figure><p>Oui, oui 🫢. Apple, avec ses budgets pharaoniques et ses armées d’ingénieurs brillants, a simplement dit : “On va générer une grosse liste.”</p><p>Pas d’algorithme sophistiqué de boucle infinie. Pas de composant UI complexe avec repositionnement dynamique. Une liste. Point final.</p><p><strong>Pourquoi ce choix ?</strong> Très certainement pour des questions de performance. Repositionner dynamiquement les éléments en haut de la liste tout en gardant un défilement ultra-fluide à 60fps, c’était probablement trop coûteux en ressources. Alors plutôt que de se battre contre les contraintes du moteur de rendu iOS, ils ont pris le chemin de la simplicité brutale.</p><h3>Train-hat</h3><p>Restons dans l’absurde: la séquence de métro Fallout 3.</p><p>Dans ce jeu, tu as l’occasion de voyager tranquillement dans un wagon de métro post-apocalyptique, regardant le tunnel défiler par les fenêtres ? Une immersion dans les entrailles souterraines d’un Washington DC post-apocalyptique.</p><p>Eh bien, tu n’es <strong>pas</strong> dans un train. Tu as juste un chapeau de métro sur la tête et tu cours très vite sur les rails.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FEVFfHNn0VYw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fshorts%2FEVFfHNn0VYw&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FEVFfHNn0VYw%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2be7831f8bb48cf46d43715ef3564387/href">https://medium.com/media/2be7831f8bb48cf46d43715ef3564387/href</a></iframe><p>Oui, oui 🫢. Bethesda, le studio derrière l’une des plus grandes franchises RPG de tous les temps, a littéralement équipé le joueur d’un énorme modèle 3D de train sur la tête, l’a fait courir à toute vitesse le long des rails, et a déposé la camera en vue première personne.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NCxphNxrf3uoHOR9.png" /><figcaption>Et oui, c’est juste toi qui court vite avec un chapeau de train — Tchu Tchu 🚂 🎩</figcaption></figure><p><strong>Pourquoi ce choix ?</strong> Le moteur Gamebryo (celui de Fallout 3) ne supportait tout simplement pas les véhicules en mouvement. Pas de système de physique pour gérer les transports, pas de caméra adaptée, rien. Bethesda aurait pu passer des mois à créer un système complet de véhicules… pour une seule séquence de 2 minutes.</p><p>Alors ils ont pris le chemin du génie bricolé : utiliser ce qui existait déjà (le joueur, l’équipement, les animations de course et la camera) et les détourner complètement de leur usage initial.</p><h3>Illusion of desilusion</h3><p>Parlons maintenant d’une illusion que tu as probablement vécue sans jamais t’en rendre compte : le sprint à cheval dans les jeux vidéo.</p><p>Dans une grande majorité des jeux, tu as deux vitesses de déplacement : marcher ou courir. À cheval, c’est pareil : le trot ou le galop. Tu appuies sur la touche sprint, ton cheval s’emballe, la crinière au vent, et tu <em>sens</em> cette poussée d’adrénaline. Tu vas clairement plus vite, non ?</p><p>Eh bien, dans Dragon Age: Inquisition… <strong>non</strong>. Tu ne vas pas plus vite. Pas du tout. Ton cheval trotte exactement à la même vitesse qu’avant.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FvqqJlTe-ARw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fshorts%2FvqqJlTe-ARw%3Fsi%3DhrUHeIOjXkNdltLw&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FvqqJlTe-ARw%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab1086c1ed564fcfa4d61411dec1b4b4/href">https://medium.com/media/ab1086c1ed564fcfa4d61411dec1b4b4/href</a></iframe><p>Oui, oui 🫢. BioWare, le studio derrière Mass Effect, t’a menti en te regardant bien dans les yeux. Quand tu “sprintes” à cheval, la vitesse réelle ne change pas d’un pixel. Ils ont tout simplement ajouté des effets de vitesses et décalé la caméra pour te donner une impression de vitesse accrue.</p><p><strong>Pourquoi ce choix ?</strong> Le moteur Frostbite (oui, celui de Battlefield) ne pouvait pas charger les environnements de Dragon Age assez rapidement pour supporter une vraie augmentation de vitesse du cheval. Si tu allais réellement plus vite, tu te serais retrouvé face à des textures non chargées, du pop-in constant, voire des crashs.</p><p>Alors plutôt que de refondre tout le système de streaming des assets, BioWare a opté pour la solution la plus rapide : te faire <em>croire</em> que tu vas plus vite pour <em>donner l’impression</em> que tu vas plus vite. Et devine quoi ? Ça marche à la perfection.</p><blockquote>Ce qui compte, c’est le <em>ressenti</em>. Et le ressenti, lui, est authentique.</blockquote><h3>Sky is the limit</h3><p>Continuons avec un classique de la Nintendo 64 : le ciel The Legend of Zelda: Ocarina of Time.</p><p>Tu te souviens de ces moments où tu levais les yeux vers le firmament d’Hyrule ? Ce ciel qui semblait s’étendre à l’infini, avec ses nuages qui défilent paisiblement, créant cette atmosphère épique et contemplative qui a marqué toute une génération de joueurs ?</p><p>Eh bien, ce n’est <strong>pas</strong> un vrai ciel. C’est juste… une grosse boîte en carton retournée autour de ta tête.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/dannyb21892/status/1564730509875355650&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd50007c5b2f5348089454df4ccc3189/href">https://medium.com/media/fd50007c5b2f5348089454df4ccc3189/href</a></iframe><p>Oui, oui 🫢. Nintendo, les maîtres absolus du game design et de l’optimisation, n’ont pas créé de système atmosphérique complexe. Ils ont simplement pris un cube géant, l’ont retourné, ont collé des textures de ciel dessus, et t’ont mis au milieu.</p><p><strong>Pourquoi ce choix ?</strong> La Nintendo 64, aussi révolutionnaire soit-elle pour l’époque, n’avait tout simplement pas la puissance pour calculer un ciel réaliste. Pas de shaders sophistiqués pour la dispersion de la lumière, pas de calculs de Rayleigh scattering, pas de nuages volumétriques en temps réel.</p><p>Alors Nintendo a fait ce que Nintendo fait de mieux : prendre une contrainte technique et en faire une force artistique. Une simple boîte texturée, toujours centrée sur le joueur pour donner l’illusion d’un horizon infini, avec juste assez de détails pour que ton cerveau comble les blancs.</p><blockquote>L’art du hack, c’est savoir quand la simplicité est ton meilleur allié.</blockquote><h3>Memory overflow</h3><p>Restons dans l’univers de Zelda, mais sautons quelques années en avant avec Breath of the Wild et son événement le plus iconique : la Blood Moon.</p><p>Tu connais la scène : le ciel vire au rouge sang, une musique inquiétante s’élève, Zelda te parle en voix off pour t’avertir que la puissance de Ganon renaît, et tous les ennemis que tu as péniblement massacrés réapparaissent. Un moment narratif fort, chargé de sens, qui renforce l’omniprésence du mal à travers Hyrule, non ? Et qui survient à interval régulier pour regénérer la. boucle de gameplay du jeu.</p><p>Eh bien, c’est surtout… un <strong>garbage collector déguisé en cinématique épique</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2F94IfptlEMRc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fshorts%2F94IfptlEMRc&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2F94IfptlEMRc%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3ce39c82524a3d20af1f1c29798ed75/href">https://medium.com/media/b3ce39c82524a3d20af1f1c29798ed75/href</a></iframe><p>Oui, oui 🫢. Nintendo, ont encore une fois transformé une contrainte technique critique en événement scénaristique. Quand la Switch commence à suffoquer sous le poids de toutes tes actions (objets ramassés, ennemis tués, arbres coupés, état du monde modifié), le jeu déclenche une Blood Moon pour vider la RAM.</p><p><strong>Pourquoi ce choix ?</strong> Breath of the Wild est un monde ouvert gigantesque où <em>tout</em> est persistent et interactif. Chaque pomme ramassée, chaque bokoblin tué, chaque coffre ouvert reste en mémoire. Sur une console portable avec des ressources limitées, ça devient vite ingérable.</p><p>Au lieu de laisser forcer des écrans de chargement, Nintendo a eu un coup de génie : transformer cette nécessité technique en moment de gameplay. La Blood Moon n’est pas un bug, c’est une <em>feature</em>. Elle a un sens narratif, elle crée de la tension, elle te force à rester vigilant, et surtout… personne ne se doute qu’elle sauve ton jeu du crash.</p><h3>Not a bug — a feature</h3><p>Pour terminer cette galerie de hacks, je te garde le meilleur pour la fin. L’alpha et l’oméga du hack devenu légende : Space Invaders (1979).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*TQhZ2T9eCOy1O3yU.gif" /></figure><p>Tu connais forcément ce jeu mythique, même si tu ne l’as jamais touché. Et tu connais surtout <em>ce</em> moment : au début, les aliens descendent tranquillement, presque paresseusement. Mais au fil de la partie, ils accélèrent. De plus en plus vite. Jusqu’à cette tension insoutenable où tu peux à peine respirer entre deux tirs. C’est l’essence même du gameplay, la montée dramatique parfaite, le game design à l’état pur.</p><p>Sauf que cette accélération progressive, ce crescendo parfaitement calibré… <strong>personne ne l’a programmée</strong>.</p><p>Oui, oui 🫢. Il n’y a <strong>aucune ligne de code</strong> dans Space Invaders pour accélérer le jeu. Zéro. Nada. Rien.</p><p><strong>La vérité ?</strong> Au début de la partie, les processeur de 1979 sont <em>saturés</em>. Calculer le mouvement de 55 aliens, gérer toutes les collisions possibles, jouer la musique iconique (bip… bip… bip…), afficher tout à l’écran. Il rame comme un forcené. Le jeu tourne lentement parce que le CPU est à genoux.</p><p>Mais quand tu tues des aliens, magie : le processeur a moins de travail. Moins d’entités à déplacer, moins de collisions à calculer, moins de sprites à afficher. Il respire. Et comme la boucle de jeu tourne “aussi vite que possible”, elle… tourne plus vite. Naturellement. Mécaniquement.</p><blockquote>Un bug de performance transformé en feature. Génie absolu.</blockquote><h3>Sumup</h3><p>La prochaine fois que tu te retrouves à rusher ton code et à regarder ton hack un peu sale en te demandant si tu es un imposteur, rappelle-toi :</p><blockquote><strong>L’horloge d’Apple, c’est juste une grosse liste d’heures.</strong><br><strong>Tu voyages dans Fallout grâce à ton chapeau-train.</strong><br><strong>Ton cheval au galop dans Dragon Age c’est de la poudre aux yeux.<br>Le ciel de Zelda, c’est une boîte en carton.</strong><br><strong>La Blood Moon sauve ta Switch du crash.</strong><br><strong>Space Invaders accélère parce que le processeur respire mieux.</strong></blockquote><p>Les meilleurs développeurs ne sont pas ceux qui n’ont jamais fait de workaround. Ce sont ceux qui savent <strong>quand</strong> faire un hack, <strong>comment</strong> le documenter proprement, et <strong>quand</strong> revenir le nettoyer.</p><p>Le code parfait n’existe pas. Le code qui change la vie des gens, oui.</p><p>❤️ Cœur sur vos claviers.</p><h3>Sources</h3><p><strong>Outsidexbox</strong> (Mars 2023) 7 Videogame Workarounds That Will Blow Your Mind.<br><a href="https://www.youtube.com/watch?v=9uJLU539NA8">https://www.youtube.com/watch?v=9uJLU539NA8</a></p><p><strong>Nicolae Berbece</strong> (Mai 2020) It’s OK to not know what you are doing.<br><a href="https://youtu.be/FQiDz0qhzjA?si=3GvkGLDgLQkyw5ON">https://youtu.be/FQiDz0qhzjA?si=3GvkGLDgLQkyw5ON</a></p><p><strong>Reddit</strong> (Août 2025) Phone alarm numbers aren’t in an endless loop,<br><a href="https://www.reddit.com/r/iphone/comments/1mujz7e/til_iphone_alarm_numbers_arent_in_an_endless_loop/">https://www.reddit.com/r/iphone/comments/1mujz7e/til_iphone_alarm_numbers_arent_in_an_endless_loop</a></p><p><strong>Daniel Baamonde</strong> (Août 2022) OoT Skybox,<br><a href="https://x.com/dannyb21892/status/1564730509875355650">https://x.com/dannyb21892/status/1564730509875355650</a></p><p><strong>Ana Diaz</strong> (Août 2023) Zelda: Tears of the Kingdom’s blood moon has a secret purpose.<br><a href="https://www.polygon.com/legend-zelda-tears-kingdom/23834440/totk-blood-moon-hidden-trick/">https://www.polygon.com/legend-zelda-tears-kingdom/23834440/totk-blood-moon-hidden-trick</a></p><p><strong>Phil Savage</strong> (Juillet 2015) Here’s what’s really powering Fallout 3’s metro train.<br><a href="https://www.pcgamer.com/heres-whats-happening-inside-fallout-3s-metro-train/">https://www.pcgamer.com/heres-whats-happening-inside-fallout-3s-metro-train</a></p><p><strong>Darren</strong> (Mars 2016) How exactly did [arcade] Space Invaders get faster with fewer aliens?<a href="https://retrocomputing.stackexchange.com/questions/31423/how-exactly-did-arcade-space-invaders-get-faster-with-fewer-aliens">https://retrocomputing.stackexchange.com/questions/31423/how-exactly-did-arcade-space-invaders-get-faster-with-fewer-aliens</a></p><h3>Resources</h3><p><strong>Claude AI, </strong><a href="https://claude.ai/">https://claude.ai</a><br>Aider à la rédaction à affinage des textes.</p><p><strong>Imagen, </strong><a href="https://deepmind.google/models/imagen/">https://deepmind.google/models/imagen/</a><br>Generated the very accurate article’s cover illustration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34f1890117cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>