<?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 Talhaoui mouad on Medium]]></title>
        <description><![CDATA[Stories by Talhaoui mouad on Medium]]></description>
        <link>https://medium.com/@talhaouimouad04?source=rss-333bd8fc8ddc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YeDZ3jdi6cA3ZvRM6KrQ8g.jpeg</url>
            <title>Stories by Talhaoui mouad on Medium</title>
            <link>https://medium.com/@talhaouimouad04?source=rss-333bd8fc8ddc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:01:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@talhaouimouad04/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[Les Sealed classes et interfaces en Java]]></title>
            <link>https://medium.com/@talhaouimouad04/les-sealed-classes-et-interfaces-en-java-5aa8d879d126?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa8d879d126</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 21:50:36 GMT</pubDate>
            <atom:updated>2026-10-02T21:50:36.384Z</atom:updated>
            <content:encoded><![CDATA[<p>En Java classique, une classe est soit final (aucun sous-type), soit ouverte à n’importe quel sous-type, y compris dans du code tiers. Il n’existait pas de position intermédiaire pour dire : «une Forme est soit un Cercle, soit un Rectangle, soit un Triangle, et rien d’autre»</p><p>. Conséquences :</p><ul><li>le compilateur ne peut pas vérifier qu’un traitement couvre tous les cas;</li><li>les chaînes if/else instanceof se terminent par un else défensif inutile;</li><li>l’ajout d’un nouveau sous-type passe inaperçu dans le code client.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObPp8l7ToboHCSF1CbxQ5A.png" /><figcaption>Les Sealed classes et interfaces en Java</figcaption></figure><p><strong>1- Syntaxe : sealed et permits:</strong></p><p>Une classe ou interface scellée (sealed) restreint l’ensemble de ses sous-types directs à une liste explicitement autorisée par la clause permits.</p><pre>public abstract sealed class Vehicule permits Voiture, Camion, Moto { }</pre><p>Chaque sous-classe autorisée doit obligatoirement déclarer un et un seul des modificateurs suivants :</p><p><strong>a- final:</strong></p><p>La hiérarchie s’arrête ici (aucun sous-type).</p><p><strong>b- sealed:</strong></p><p>La sous-classe est elle-même scellée et déclare ses propres permits.</p><p><strong>c-non-sealed:</strong></p><p>La sous-classe rouvre la hiérarchie : n’importe qui peut en hériter.</p><pre>public abstract sealed class Vehicule permits Voiture, Camion, Moto { }<br><br>public final class Voiture extends Vehicule { } // feuille<br><br>public non-sealed class Camion extends Vehicule { } // rouvert<br>public class SemiRemorque extends Camion { } // autorisé<br><br>public sealed class Moto extends Vehicule permits Scooter { } // re-scellé<br>public final class Scooter extends Moto { }</pre><p><strong>2- Interfaces scellées:</strong></p><p>Les interfaces peuvent également être scellées; leurs implémentations autorisées peuvent être des classes, des records (implicitement final) ou d’autres interfaces (sealed ou non-sealed) :</p><pre>public sealed interface Forme permits Cercle, Rectangle, Triangle { }<br><br>public record Cercle(double r) implements Forme { }<br>public record Rectangle(double l, double h) implements Forme { }<br>public record Triangle(double b, double h) implements Forme { }</pre><p>Un record étant implicitement final, il satisfait automatiquement l’exigence de modificateur : aucune annotation supplémentaire n’est nécessaire. De même, une enum peut implémenter une interface scellée.</p><p><strong>3- Règles de compilation:</strong></p><ol><li>Localité. Les sous-classes autorisées doivent appartenir au même module que la classe scellée; si le code n’est pas modulaire (module anonyme), au même package.</li><li>Héritage direct. Chaque classe listée dans permits doit étendre directement la classe scellée.</li><li>Modificateur obligatoire. Chaque sous-classe directe est final, sealed ou non-sealed.</li><li>Omission de permits. Si toutes les sous-classes sont déclarées dans le même fichier source, la clause permits peut être omise : le compilateur infère la liste. 5. Accessibilité. Les sous-classes doivent être accessibles depuis la classe scellée à la compilation.</li></ol><p>Violation de la règle d’autorisation :</p><pre>sealed interface F permits C {}<br>record C() implements F {}<br>final class Z implements F {} // non listée dans permits</pre><p>error: class is not allowed to extend sealed class: F</p><p>F (as it is not listed in its ‘permits’ clause)</p><p>Omission de permits dans un seul fichier :</p><pre>// Fichier Arbre.java<br>public sealed interface Arbre&lt;T&gt; {<br> record Feuille&lt;T&gt;(T valeur) implements Arbre&lt;T&gt; { }<br> record Noeud&lt;T&gt;(Arbre&lt;T&gt; gauche, Arbre&lt;T&gt; droite) implements Arbre&lt;T&gt; { }<br>} // permits inféré : Feuille, Noeud</pre><p><strong>4- Réflexion:</strong></p><pre>Forme.class.isSealed(); // true<br>Forme.class.getPermittedSubclasses(); // [Cercle, Rectangle, Triangle]</pre><p><strong>5- Intérêt en conception:</strong></p><ul><li>Modélisation du domaine : exprimer explicitement que Paiement est Carte, Virement ou Especes.</li><li>API publiques : une bibliothèque peut exposer une interface publique tout en interdisant les implémentations externes (évolution maîtrisée).</li><li>Sécurité : empêcher l’injection de sous-types malveillants dans un framework.</li><li>Exhaustivité : le compilateur vérifie que tous les cas sont traités (section suivante).</li></ul><p><strong>6- Records + Sealed : types algébriques et pattern matching:</strong></p><p>a- Types produit et types somme:</p><p>Type de données algébrique</p><ul><li>Un type produit combine plusieurs valeurs simultanément («A et B») : c’est le record.</li><li>Un type somme représente une valeur parmi plusieurs alternatives («A ou B») : c’est l’interface scellée.</li><li>Leur combinaison forme un type algébrique (ADT).</li></ul><p>Le nombre de valeurs possibles illustre la terminologie : un record (boolean, boolean) admet 2 × 2 = 4 valeurs, tandis qu’une somme Boolean | Unit en admet 2 + 1 = 3.</p><p>b- Pattern matching pour instanceof (Java 16):</p><pre>// Avant<br>if (f instanceof Cercle) {<br>  Cercle c = (Cercle) f;<br>  return Math.PI * c.r() * c.r();<br>}<br>// Depuis Java 16 : motif de type<br>if (f instanceof Cercle c) {<br>  return Math.PI * c.r() * c.r();<br>}<br>// Java 21 : motif de record (déconstruction)<br>if (f instanceof Cercle(double r)) {<br>  return Math.PI * r * r;<br>}</pre><p>c- Pattern matching pour switch (Java 21):</p><p>Le switch accepte désormais des motifs. Sur un type scellé, le compilateur vérifie l’exhaustivité : aucun default n’est requis.</p><pre>static double aire(Forme f) {<br>  return switch (f) {<br>    case Cercle c -&gt; Math.PI * c.r() * c.r();<br>    case Rectangle(double l, double h) -&gt; l * h;<br>    case Triangle(var b, var h) -&gt; b * h / 2;<br>  };<br>}</pre><p>Si l’on oublie un cas :</p><p>error: the switch expression does not cover all possible input values</p><p>Pourquoi ne pas mettre de default:</p><p>Un default désactive la vérification d’exhaustivité. Sans lui, l’ajout d’une variante Hexagone dans la clause permits provoque une erreur de compilation dans chaque switch non mis à jour : le compilateur devient un outil de refactoring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa8d879d126" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Les Records en Java]]></title>
            <link>https://medium.com/@talhaouimouad04/les-records-en-java-650bd4617af4?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/650bd4617af4</guid>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 21:32:02 GMT</pubDate>
            <atom:updated>2026-10-02T21:32:02.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOD4JJIFjQio9kfaU8dHyA.png" /><figcaption>Records En Java</figcaption></figure><p>Depuis sa creation, Java a été critiqué pour sa verbosité lorsqu’il s’agit de representer de simples agrégats de données: un objet portant 3 champs nécessitait un constructeurn 3 getters et d’autres methodes, c’est à dire plusieurs dizaines de lignes pour une information triviale. En meme sens le langage ne permettait pas d’exprimer qu’une hiérarchie de types est fermée.</p><p>Le projet Amber d’openJDK a répondu à ces 2 limites par 2 fonctionnalités complémentaires:</p><ul><li>Les <strong>Records </strong>qui modelisent des agrégats de données immutables et transparents.</li><li>Les <strong>Sealed classes/ interfaces</strong> qui modélisent des alternatives fermées.</li></ul><p>Combinés au pattern matching (instanceof, switch, motifs de records), elles apportent en Java la notion de types de données algébriques (ADT), bien connue des langages fonctionnels(Scala, Kotlin, Rust, …).</p><h3>1- Les Records:</h3><p><strong>1–1- Solution 1:(classe de données classique):</strong></p><p>Considerons un point du plan, ecrit à l’ancienne de manière correcte (immuable, avec egalité par valeur);</p><pre>public final class Point {<br>  private final int x;<br>  private final int y;<br> <br>  public Point(int x, int y) { this.x = x; this.y = y; }<br> <br> public int x() { return x; }<br><br>public int y() { return y; }<br><br>   @Override<br>   public boolean equals(Object o) {<br>   if (this == o) return true;<br>   if (!(o instanceof Point)) return false;<br>   Point p = (Point) o;<br>   return x == p.x &amp;&amp; y == p.y;<br> }<br>   @Override<br>   public int hashCode() { return Objects.hash(x, y); }<br>  <br>   @Override<br>   public String toString() { return &quot;Point[x=&quot; + x + &quot;, y=&quot; + y + &quot;]&quot;; }<br>   }</pre><p>Ce code est long,répétitif et fragile: ajouter un chanp z oblige à modifier 5 endroits, et oublier hashCode casse silencieusement les HashMap.</p><p><strong>1–2- Solution 2: Déclaration d’un record:</strong></p><p>Un record est une classe sépciale, déclarée par le mot-clé contextuel <strong>record, </strong>dont l’état est entièrement défini par une liste de composants. C’est un proteur de données transparent et immuable.</p><pre>public record Point(int x, int y) { }</pre><p><strong>1–3: Ce que le compilateur génère:</strong></p><p>Pour un Record R(T1 c1, ….., Tn cn), le compilateur produit automatiquemen:</p><p>1- Un champ private final Ti ci par composant;</p><p>2- Un constructeur canonique R(T1 c1, …… , Tn cn) qui initialise chaque champ;</p><p>3- Un accesseur public Ti ci() par composant sans prefixe get;</p><p>4- Une methode equals: 2 records sont égaux s’ils sont de meme classe et si tous leurs componsants sont égaux;</p><p>5- Une méthode hashCode cohérente avec equals;</p><p>6- Une méthode toString au format R[c1=v1,….,cn=vn]</p><p>Pour l’exemple deja cité javac génére le code :</p><pre>final class Point extends java.lang.Record {<br>    private final int x;<br>    private final int y;<br>    Point(int x, int y) { ... } // canonique<br>    public int x() { ... }<br>    public int y() { ... }<br>    equals / hashCode / toString<br>}</pre><p>Et on peut l’utiliser comme ca:</p><pre>Point p = new Point(3, 4);<br>System.out.println(p); // Point[x=3, y=4]<br>System.out.println(p.x()); // 3<br>System.out.println(p.equals(new Point(3,4))); // true<br>Set&lt;Point&gt; s = new HashSet&lt;&gt;(List.of(p, new Point(3, 4)));<br>System.out.println(s.size());</pre><p><strong>1–4: Propriétés et restrictions:</strong></p><p>Un record est volontairement contraint afin de garantir sa transparence:</p><p><strong>a- Final:</strong></p><p>Les records sont implicitement final et par conséquent, on peut pas hériter d’un record.</p><p><strong>b- java.lang.Record:</strong></p><p>Les records hérite implicitement de java.lang.Record et par conséquent, on a pas de clause extedns possible.</p><p><strong>c- private final:</strong></p><p>Les champs des records sont private final et par conséquent, l’état est immuable (immutablité superficielle).</p><p><strong>d- Interdiction de champs d’instance:</strong></p><p>Seuls des champs static sont autorisés.</p><p><strong>e- Initialiseur d’instance:</strong></p><p>Les blocs {…} non statiques sont interdits.</p><p><strong>1–5: Les constructeurs d’un record:</strong></p><p><strong>a- Constructeur compact (Validation et normalisation):</strong></p><p>Le constructeur compact est la forme idiomatique pour valider ou normaliser les paramètres. Il ne déclare pas de liste paramètres: ceux-ci sont implicites, et l’affectation des champs est insérée automatiquent à la fin par le compilateur.</p><pre>public record Point(int x, int y) {<br>public Point { // constructeur compact<br>if (x &lt; 0 || y &lt; 0)<br>throw new IllegalArgumentException(&quot;Coordonnées négatives&quot;);<br>} // this.x = x; this.y = y; ajoutés implicitement ici<br>}</pre><p>On peut réaffecter les paramètres (pas les champs) pour normaliser :</p><pre>public record Etudiant(String nom, List&lt;Double&gt; notes) {<br>public Etudiant {<br>Objects.requireNonNull(nom, &quot;nom obligatoire&quot;);<br>nom = nom.strip(); // normalisation<br>notes = List.copyOf(notes); // copie défensive immuable<br>}<br>}</pre><p>NB:</p><p>Dans un constructeur compact, écrire this.nom = … est interdit : l’affectation des champs est réservée au compilateur. On manipule uniquement les paramètres implicites.</p><p><strong>b- Le constructeur canonique explicite:</strong></p><p>On peut aussi écrire le constructeur canonique en entier; il doit alors affecter tous les champs et avoir exactement la même signature que l’en-tête :</p><pre>public record Intervalle(int debut, int fin) {<br>public Intervalle(int debut, int fin) {<br>  if (debut &gt; fin) { int t = debut; debut = fin; fin = t; }<br>    this.debut = debut;<br>    this.fin = fin;<br>  }<br>}</pre><p>Le constructeur canonique (compact ou explicite) doit être au moins aussi accessible que le record lui-même. On ne peut pas déclarer les deux formes simultanément.</p><p><strong>c- Constructeurs secondaires et fabriques statiques:</strong></p><p>Tout constructeur non canonique doit déléguer, directement ou indirectement, au constructeur canonique via this(…) :</p><pre>   public record Point(int x, int y) {<br>   public static final Point ORIGINE = new Point(0, 0);<br><br>   public Point(int v) { this(v, v); } // délégation obligatoire<br><br>   public static Point polaire(double r, double theta) { // fabrique<br>       return new Point((int) Math.round(r * Math.cos(theta)),<br>       (int) Math.round(r * Math.sin(theta)));<br>     }<br>   }</pre><p><strong>1–6:Méthodes, membres statiques et interfaces:</strong></p><p>Un record reste une classe : il peut définir des méthodes d’instance, des méthodes et champs statiques, des types imbriqués, et implémenter des interfaces</p><pre> public record Point(int x, int y) implements Comparable&lt;Point&gt; {<br><br> public double distance(Point o) {<br>   return Math.hypot(x - o.x, y - o.y); // accès direct aux champs<br> }<br><br> // « wither » : renvoie une copie modifiée (le record reste immuable)<br> public Point withX(int nx) { return new Point(nx, y); }<br><br> @Override<br> public int compareTo(Point o) {<br>   return Comparator.comparingInt(Point::x)<br>   .thenComparingInt(Point::y)<br>   .compare(this, o);<br>  }<br>}</pre><p><strong>a- Redéfinir les méthodes générées:</strong></p><p>Les accesseurs, equals, hashCode et toString peuvent être redéfinis, à condition de respecter le contrat du record : un accesseur redéfini doit être public, avoir le même type de retour, et ne pas lever d’exception vérifiée.</p><pre>public record MotDePasse(String valeur) {<br>  @Override<br>  public String toString() { return &quot;MotDePasse[****]&quot;; } // masquage<br>}</pre><p>Pour tout record r, on doit avoir : new R(r.c1(), …, r.cn()).equals(r). Un accesseur qui renvoie une valeur différente du champ (par ex. une valeur transformée) viole ce contrat et casse la déconstruction par motifs ainsi que la sérialisation.</p><p><strong>1–7:Immutabilité superficielle:</strong></p><p>Les champs d’un record sont final, mais les objets référencés ne sont pas figés pour autant :</p><pre>record Panier(List&lt;String&gt; articles) {}<br><br>List&lt;String&gt; l = new ArrayList&lt;&gt;(List.of(&quot;stylo&quot;));<br>Panier p = new Panier(l);<br>l.add(&quot;cahier&quot;); // modifie l&#39;état &quot;interne&quot; du record !<br>System.out.println(p); // Panier[articles=[stylo, cahier]]</pre><p>Pour un record réellement immuable, effectuez une copie défensive dans le constructeur compact : articles = List.copyOf(articles);</p><p>List.copyOf renvoie une liste non modifiable (et rejette les null). Toute tentative d’écriture lève UnsupportedOperationException.</p><p><strong>1–8: Records génériques, imbriqués et locaux:</strong></p><pre> // Générique : un tuple typé<br>record Paire&lt;A, B&gt;(A gauche, B droite) {<br>  static &lt;A, B&gt; Paire&lt;A, B&gt; de(A a, B b) { return new Paire&lt;&gt;(a, b); }<br>}<br><br>class Statistiques {<br>  // Imbriqué : implicitement static<br>  record MinMax(double min, double max) {}<br><br>  static MinMax bornes(double[] v) {<br>    return new MinMax(Arrays.stream(v).min().orElseThrow(),<br>    Arrays.stream(v).max().orElseThrow());<br>  }<br><br>  static List&lt;String&gt; top3(Map&lt;String, Integer&gt; ventes) {<br>    // Local : déclaré dans une méthode, idéal pour les calculs intermédiaires<br>    record Vente(String produit, int qte) {}<br>    return ventes.entrySet().stream()<br>    .map(e -&gt; new Vente(e.getKey(), e.getValue()))<br>  .sorted(Comparator.comparingInt(Vente::qte).reversed())<br>.limit(3)<br>.map(Vente::produit)<br>.toList();<br>}<br>}</pre><p>Les records locaux (ainsi que les interfaces et énumérations locales) sont implicitement static : ils ne peuvent pas capturer les variables locales de la méthode englobante</p><p><strong>2–9: Annotations sur les composants:</strong></p><p>Une annotation placée sur un composant est propagée vers les éléments générés compatibles avec sa cible (@Target) : champ, paramètre du constructeur canonique, accesseur, composant de record</p><pre>public record Utilisateur(<br>  @NotBlank String login,<br>  @Email String email,<br>  @Min(18) int age) { }</pre><p>Ceci rend les records directement exploitables avec Bean Validation, Jackson (≥ 2.12) ou Spring (DTO de contrôleurs REST, @ConfigurationProperties).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650bd4617af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common React Errors]]></title>
            <link>https://medium.com/@talhaouimouad04/common-react-errors-6f4c71e5f1c3?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f4c71e5f1c3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[viewjs]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 10:08:50 GMT</pubDate>
            <atom:updated>2026-09-26T10:08:50.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wqxu2a4qGVTEN5WZKmEezw.jpeg" /></figure><h3>1- Objects are not valid as React child:</h3><p>When trying to render a JS object directly we face this error:</p><pre>const food = {<br>  type : &quot;fruit&quot;,<br>  count : 12<br>};<br><br>return &lt;h1&gt; {food} &lt;/h1&gt;;</pre><p>React cannot render the object itself, so we should render the attributes.</p><pre>return &lt;div&gt;<br>          &lt;h1&gt;type : {food.type}&lt;/h1&gt;<br>          &lt;h1&gt;count : {food.count}&lt;/h1&gt;<br>        &lt;/div&gt;;</pre><p>or for debugging:</p><pre>&lt;pre&gt;{JSON.stringify(food, null, 2)}&lt;/pre&gt;</pre><h3>2- Missing key Prop in Lists:</h3><p>We should pass unique key when trying to render an array.</p><pre>const fruits= [&quot;avocado&quot;, &quot;banana&quot;, &quot;apple&quot;];<br><br>return (<br>  &lt;ul&gt;<br>    {fruits.map(fruit =&gt; (<br>      &lt;li&gt;{fruit}&lt;/li&gt;<br>    ))}<br>  &lt;/ul&gt;<br>);</pre><p>you will see somthing like in console:</p><pre>Each child in a list should have a unique &quot;key&quot; prop.</pre><p>to fix it pass the key like:</p><pre>{fruits.map(fruit=&gt; (<br>  &lt;li key={fruit}&gt;{fruit}&lt;/li&gt;<br>))}</pre><p>keys help React identify which items have changed, been added, or removed.</p><h3>NB:</h3><p>Avoid using array indexes as keys when the list can be reordered or modified.</p><h3>3- Cannot read properties of undefined:</h3><p>A commponent may try to access a property before the data exists like :</p><pre>&lt;h1&gt;{fruit.type}&lt;/h1&gt;</pre><p>if the fruit is initially undefined, this can cause an error.</p><p>to fix it use optional chaining like :</p><pre>&lt;h1&gt;{fruit?.type}&lt;/h1&gt;</pre><p>Or conditionally render the component like:</p><pre>{fruit &amp;&amp; &lt;h1&gt;{fruit.type}&lt;/h1&gt;}</pre><h3>4- Updating State Incorrectly:</h3><p>State updates should use the state setter rather than directly modifying the state variable.</p><p>Error:</p><pre>count = count + 1;</pre><p>Fix:</p><pre>setCount(count+1);</pre><h3>5- Infinite useEffect Loops:</h3><p>An incorreclty configured effect can run cotinuously.</p><pre>useEffect(() =&gt; {<br>  setCount(count+1);<br>}, [count]);</pre><p>the effect changes count, which causes the effect to run again, creating a loop. The solution for this problem depends on the intended behavior. If he effect should run only once when the component mounts:</p><pre>useEffect(() =&gt; {<br>  // logic<br>}, []);</pre><h3>6- Calling Hooks Conditionally:</h3><p>Hooks must be called in the same order on every render</p><p><strong>Error:</strong></p><pre>if (isLoggedIn) {<br>  useEffect(() =&gt; {<br>    // ...<br>  }, []);<br>}</pre><p><strong>Fix:</strong></p><pre>useEffect(() =&gt; {<br>  if (isLoggedIn) {<br>    // ...<br>  }<br>}, [isLoggedIn]);</pre><p>The same rule appliesto useState, useMemo, use Callback, and other Hooks.</p><h3>7- Incorrect Event Handler:</h3><p>This mistake calls the function immedialtely instead of passing it as an event handler.</p><p>ERRor:</p><pre>&lt;button onClick={handleClick()}&gt;<br>  Click<br>&lt;/button&gt;</pre><p>Fix:</p><pre>&lt;button onClick={handleClick}&gt;<br>  Click<br>&lt;/button&gt;</pre><p>if the args are required:</p><pre>&lt;button onClick={() =&gt; handleClick(id)}&gt;<br>  Click<br>&lt;/button&gt;</pre><h3>8- Using class instaed of className:</h3><p>JSX uses className for CSS classes because class is a JS keyword-related attribute confict in JSX’s DOM property model.</p><h3>9- Component Name starts with a Lowercase Letter:</h3><p>use PascalCase because React treats lowercase JSX tags as HTML elements.</p><pre>function phone(){<br>  return &lt;h1&gt;phone&lt;/h1&gt;; <br>}<br>&lt;phone/&gt;</pre><p>React interprets &lt;phone/&gt; as custom HTML-like element rather than your React component.</p><h3>10- State Updates Don’t Happen Immediately:</h3><p>This can be confusing:</p><pre>setCount(count+1);<br>console.log(count);</pre><p>The console.log may still show the previous value because React schedules state updates rather than changing the variable immediately.</p><p>Fix:</p><pre>useEffect(() =&gt; {<br>  console.log(count);<br>}, [count]);</pre><h3>11- Props Are Read-Only:</h3><p>You should not directly modify props inside a component.</p><p>Error:</p><pre>function User({ name }) {<br>  name = &quot;Mike&quot;;<br><br>  return &lt;h1&gt;{name}&lt;/h1&gt;;<br>}</pre><p>Instead, use state if the component needs to manage a changing value:</p><pre>function User({ name }) {<br>  const [currentName, setCurrentName] = useState(name);<br><br>  return &lt;h1&gt;{currentName}&lt;/h1&gt;;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f4c71e5f1c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Les 5 erreurs les plus fréquentes dans le développement Spring Boot]]></title>
            <link>https://medium.com/@talhaouimouad04/les-5-erreurs-les-plus-fr%C3%A9quentes-dans-le-d%C3%A9veloppement-spring-boot-2b9edf672c00?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b9edf672c00</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 13:13:45 GMT</pubDate>
            <atom:updated>2026-09-25T13:13:45.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOhU8eQirX0-J59bZSaueQ.png" /></figure><h3>1- Utiliser @Autowired partout:</h3><p>L’injection par champ rend le code moins testable, plus rigide et masque les dépendences.</p><p><strong>Erreur:</strong></p><pre>@Service<br>public class UserService { <br><br>  @Autowired<br>  private UserRepository userRepository;<br>  <br>  @Autowired<br>  private MailService mailService;<br><br>  public void register(User user) {<br>    //...<br>  }<br>}</pre><p>Dépendences invisibles, difficiles à tester, fort couplage au container Spring.</p><p><strong>Correction:</strong></p><pre>@Service<br>public class UserService { <br><br>  private final UserRepository userRepository;<br>  private final MailService mailService;<br><br>  public UserService(UserRepository userRepository,MailService mailService) {<br>    this.userRepository = userRepository;<br>    this.mailService = mailService;<br>  }<br>  <br>  public void register(User user) {<br>    //...<br>  }<br>}</pre><p>Dépendances explicites,code testable, faible couplage et meilleure maintenabilité.</p><h3>2- Mettre toute la logique métier dans les Controllers:</h3><p>Séparez les responsabilités par controller ( Recoit la requete et delegue ), service ( Contient la logique métier ), et Repository ( Accés aux données ) et rapplez vous qu’un code propre commence par une architecture propre.</p><h3>3- Exposer directement les Entités JPA:</h3><p>Retourner vos entités JPA firectement via vos API peut sembler pratique, mais cela cache des risques majeurs.</p><pre>@Entity<br>public class User {<br>  private Long id;<br>  private String name;<br>  private String email;<br>  private String password;<br>  private LocalDateTime createdAt;<br>  private List&lt;Order&gt; orders;<br>}</pre><p><strong>Les risques:</strong></p><p><strong><em>a- Fuite d’informations:</em></strong></p><p>Exposition de données sensibles (mots de passe, champs internes, etc.)</p><p><strong><em>b- Dépendance forte:</em></strong></p><p>Vos API deviennent dependantes du modéle JPA.</p><p><strong><em>c- Problemes de sérialisation:</em></strong></p><p>Boucles infinies, LazyInitializationException et payloads inutiles.</p><p><strong>La Solution:</strong></p><p>Utiliser les DTOs vous permettent de:</p><ul><li>Maitriser les données exposées</li><li>Découpler l’API du modèle de persistance</li><li>Améliorer les performances et la sécurité</li></ul><h3>4- Mauvaise gestion des exceptions:</h3><pre>try{<br>  //logique metier<br>} catch(Exception e){<br>  e.printStackTrace();<br>  return ResponseEntity<br>          .status(500)<br>          .body(&quot;Erreur serveur&quot;);<br>}</pre><ul><li>Capture toutes les exceptions</li><li>Informations techniques exposées</li><li>Réponse générique pour le client</li><li>Debugging et maintenance difficiles</li></ul><p><strong>Bonne pratique:</strong></p><ul><li>Gestion centralisée des exceptions via @ControllerAdvice</li><li>Messages clairs et adaptés au client</li><li>Séparation des responsabilités</li><li>Facilite le debugging et la maintenance</li></ul><h3>5- Négliger les tests:</h3><p>“Plus tard n’arrive jamais”</p><p><strong>Conséquences:</strong></p><p>régressions, peur de modifier le code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b9edf672c00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel 13 the most important Feature to care About]]></title>
            <link>https://medium.com/@talhaouimouad04/laravel-13-the-most-important-feature-to-care-about-ea35c433101d?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea35c433101d</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[eloquent]]></category>
            <category><![CDATA[php13]]></category>
            <category><![CDATA[somfony]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 17:25:03 GMT</pubDate>
            <atom:updated>2026-09-23T17:25:03.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbFwSOkq9Mb0DYxRf_7zpQ.png" /><figcaption>laravel</figcaption></figure><p>Here are the biggest additions in Laravel 13 that make writing modern laravel php code feel better than ever.</p><h3>1- First-Class PHP Attributes:</h3><p>In old laravel version, Eloquent models and queued jobs have been defined by a wall of class properties declared at the top of file but now in LAravel 13, native PHP #[Attribute] syntax is available across more than 15 locations in the framework.</p><h3>BEFORE:</h3><pre>class ProcessPayment implements ShouldQueue<br>{<br>    public $connection = &#39;redis&#39;;<br>    public $queue = &#39;payments&#39;;<br>    public $tries = 3;<br>    public $timeout = 60;<br>    <br>    // ...<br>}</pre><h3>In Laravel 13:</h3><pre>use Illuminate\Queue\Attributes\WithQueue;<br>#[WithQueue(connection: &#39;redis&#39;, queue: &#39;payments&#39;, tries: 3, timeout: 60)]<br>class ProcessPayment implements ShouldQueue<br>{<br>    // Clean, readable, and compact<br>}</pre><p>You can do the exact same thing on Eloquent models to declare fillables, hidden attributes, or custom table names:</p><pre>#[Table(&#39;users&#39;, key: &#39;user_id&#39;)]<br>#[Fillable([&#39;name&#39;, &#39;email&#39;])]<br>#[Hidden([&#39;password&#39;])]<br>class User extends Model {}</pre><h3>2- Cache::touch() — Extend Expiry Without the Overhead:</h3><p>How ofter have you needed to extend a cache key’s TTL (like a user session, an active rate limit, or a hot dashboard metric)?</p><p>Previously, extending expiry required fetchinh the cached value, modifying it, and re-storing it. That is two network operations and wasted memory serialization just to update a timestamp.</p><p>In Laravel we have Cache::touch():</p><pre>// Extend TTL by 3600 seconds without fetching or re-storing data<br>Cache::touch(&#39;user_session:123&#39;, 3600); <br>// Or extend it with a DateTime<br>Cache::touch(&#39;analytics_data&#39;, now()-&gt;addHours(6));</pre><p>Under the hood, Redis receives a single <strong>EXPIRE </strong>commmand, Memcached executes a native <strong>TOUCH, </strong>and the database driver runs a basic UPDATE? No payload transfers, no uszeless overhead.</p><h3>3- Native Semantic &amp; Vector Search:</h3><p>Building AI driven features like semantic search, RAG, recommendation engines usually meant pulling in third-party packages or setting up custom abstractions.</p><p>With the official LARAVEL AI SDK going stable alongside Laravel 13, vector query support is now baked directly into the framework. If you are using PostgreSQL with pgvector, you c run similarity queries right from the fluent query builder:</p><pre>$documents = DB::table(&#39;documents&#39;)<br>    -&gt;whereVectorSimilarTo(&#39;embedding&#39;, &#39;Best cafes with fast Wi-Fi in London&#39;)<br>    -&gt;limit(5)<br>    -&gt;get();</pre><p>Generating embeddings from raw strings, querying vectors, and connecting to models (OpenAI, Anthropic, Ollama) is now part of the core ecosystem.</p><h3>4- Native Passkey Support:</h3><p>Passwordless authentication is no longer a luxury feature that takes three days to configure properly.</p><p>Laravel 13 brings native <strong>Passkey (WebAuthn)</strong> authentication to official starter kits and Fortify. Out of the box, new applications support biometric login (Touch ID, Face ID, Windows Hello) and physical security keys.</p><p>The private keys never leave the user’s device, rendering phishing and credential-stuffing attacks useless against your auth endpoints.</p><h3>5- Centralized Queue Routing:</h3><p>If your application dispatches dozens of different queued jobs, configuring their target connections and queues inside individual job classes (or repeating arguments at every dispatch() site) can quickly turn into a maintainability mess.</p><p>Laravel 13 lets you route queue jobs centrally inside a Service Provider:</p><pre>use App\Jobs\ProcessPodcast;<br>use App\Jobs\GeneratePdfReport;<br>use Illuminate\Support\Facades\Queue;<br><br>public function boot(): void<br>{<br>    Queue::route(ProcessPodcast::class, connection: &#39;redis&#39;, queue: &#39;media&#39;);<br>    Queue::route(GeneratePdfReport::class, connection: &#39;sqs&#39;, queue: &#39;exports&#39;);<br>}</pre><p>Now your business logic just calls ProcessPodcast::dispatch($podcast), and the infrastructure topology stays isolated where it belongs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea35c433101d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Agent Skills: Generate and Review an App the Official Way]]></title>
            <link>https://medium.com/@talhaouimouad04/angular-agent-skills-generate-and-review-an-app-the-official-way-c6548833b0e3?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6548833b0e3</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescprit]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 12:08:09 GMT</pubDate>
            <atom:updated>2026-09-19T12:10:56.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39ki1HYyUKmjSxVh4hb6VQ.png" /><figcaption>Angular</figcaption></figure><h3>Bad AI Angular code without guidance:</h3><p>1-NgModules:</p><pre>@NgModules({<br>declarations : [HomeComponent],<br>})<br>export class Home{}</pre><p>2-Old forms:</p><pre>this.form = this.fb.group({<br>name : [&#39;&#39;,Validators.required]<br>});</pre><p>3-Constructor DI:</p><pre>constructor(private api : Api){}<br></pre><p>4-BehaviorSubject:</p><pre>users$ = new BehaviorSubject(<br>[],<br>);</pre><h3>Code should be written:</h3><p>1-Standalone:</p><pre>@Component({<br>selector: &#39;app-home&#39;,<br>imports: [RouterLink],<br>})<br>export class Home {}</pre><p>2-Signal forms:</p><pre>form = form(<br>  signal({name : &#39;&#39;}),<br>);</pre><p>3-inject():</p><pre>private api = inject(Api);</pre><p>4-signal():</p><pre>users = signal(<br>[],<br>);</pre><h3>The common fix is the AGENTS.md file :</h3><p>Angular ships one out of the box, which has some specific instructions for your AI agents. But the problem with that is it adds to the context bloat on every call (agent’s conversation). Secondly, it only covers common syntax because it’s included in every chat; this means that you can not really have a very huge amount of standards that you include everywhere. So it only includes the common syntax. It won’t cover all of the different best practice recommendations. Also, it does not contain testing</p><h3>The Official Angular Agent Skills:</h3><p>A developer skill is basically a repeatable prompt that the agent keeps using, but these agent skills are basically more than just prompts, so they are a rip of all the best practices that Angular recommends to use in your application, and to install it is really easy. So we use npx:</p><pre>npx skills add https://github.com/angular/skills</pre><p>The CLI installs the skills from Angular’s official repository and makes them available to compatible AI coding agents. You can also list the available skills before installing them:</p><pre>npx skills add https://github.com/angular/skills --list</pre><p>The important idea is that <strong>the skill doesn’t replace the AI agent</strong>. Think of it as giving the agent a specialized Angular knowledge layer: the agent still performs the work, while the skill provides Angular-specific instructions about how that work should be done.</p><p>Angular also provides an <strong>Angular CLI MCP server</strong>, which is complementary to the Agent Skills. The skills provide guidance and coding standards, while the MCP server gives an AI assistant tools to interact with the Angular CLI, such as generating code, analyzing a workspace, and running builds and tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6548833b0e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security Headers in PHP that Harden Every Response]]></title>
            <link>https://medium.com/@talhaouimouad04/security-headers-in-php-that-harden-every-response-e79569370d91?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79569370d91</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[somfony]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 19:01:53 GMT</pubDate>
            <atom:updated>2026-08-18T19:01:53.199Z</atom:updated>
            <content:encoded><![CDATA[<p>Security headers are server-side configurations rather than application code. They act as directives that instruct the browser on how to behave, effectively neutralizing or complicating attack vectors that would otherwise succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MunqbgEhs1fPG9iQwFkeNg.png" /><figcaption>security headers in php &amp; laravel</figcaption></figure><p>Security headers operate at the server level, eliminating the need to modify application source code. Configuring these policies via web servers or middleware instructs the browser to process responses securely, even though specific headers apply only to certain resource types.</p><p><strong>Security Headers:</strong></p><p>HTTP responses carry metadata headers that go beyond standard directives like Content-Type or Cache-Control. Security headers specifically mandate secure browser behavior, enforcing client-side protections even when application code contains flaws. For instance, Content Security Policy blocks unauthorized script execution, frame protection prevents clickjacking, and strict transport rules stop HTTPS downgrade attacks. Ultimately, security headers do not patch source code vulnerabilities they systematically increase the effort required to exploit them.</p><p><strong>Header 1 — Content-Security-Policy:</strong></p><p>Content Security Policy (CSP) is the most effective yet intricate security header to implement. It establishes a explicit whitelist defining allowed origins for all page assets, including scripts, styles, images, and frames. By instructing the browser to block any unapproved source, CSP directly neutralizes Cross-Site Scripting (XSS) attempts — preventing injected scripts from running even if they slip past application controls.</p><p>A starting point for CSP</p><pre>Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39;; style-src &#39;self&#39;; img-src &#39;self&#39; data:; font-src &#39;self&#39;; base-uri &#39;self&#39;; form-action &#39;self&#39;; object-src &#39;none&#39;; frame-ancestors &#39;none&#39;</pre><p><strong>Breaking this down:</strong></p><ul><li>default-src &#39;self&#39; — by default only load content from your own domain</li><li>script-src &#39;self&#39; — only execute scripts from your own domain</li><li>style-src &#39;self&#39; — only allow stylesheets from your own domain</li><li>img-src &#39;self&#39; data: — allow images from your domain and data URIs</li><li>font-src &#39;self&#39; — only load fonts from your domain</li><li>base-uri &#39;self&#39; — prevent attackers from injecting a base tag that redirects relative URLs</li><li>form-action &#39;self&#39; — prevent forms from submitting to external domains</li><li>object-src &#39;none&#39; — block plugins entirely</li><li>frame-ancestors &#39;none&#39; — prevent your page from being embedded in iframes anywhere</li></ul><p><strong>NB for the usage of </strong><strong>&#39;unsafe-inline&#39;:</strong></p><p>While many CSP configurations include &#39;unsafe-inline&#39;, relying on it permits inline scripts and styles to run, which severely compromises XSS defense. For production environments, prefer nonces or cryptographic hashes to validate necessary inline elements securely.</p><pre>script-src &#39;self&#39; &#39;nonce-{random-value}&#39;</pre><p>A nonce is a random value generated per request and included in both the CSP header and the script tag</p><pre>&lt;script nonce=&quot;a123&quot;&gt;<br>    // inline script here<br>&lt;/script&gt;</pre><p><strong>frame-ancestors vs </strong><strong>frame-src :</strong></p><ul><li><strong>frame-ancestors:</strong> Defines who can embed <em>your</em> site in an iframe (mitigates clickjacking).</li><li><strong>frame-src:</strong> Defines what external content <em>your site</em> can embed inside an iframe.</li><li><strong>Best Practice:</strong> Set both to &#39;none&#39; if your app neither embeds third-party content nor permits framing by external sites.</li></ul><p><strong>Deploying via Report-Only Mode</strong> Configuring CSP is notoriously difficult because every external asset — such as Google Analytics, CDNs, or custom fonts — must be explicitly whitelisted. To avoid breaking production, deploy first using Content-Security-Policy-Report-Only. This directive captures and logs compliance violations without blocking traffic, allowing you to audit and refine your policy before enabling strict enforcement.</p><p><strong>Starting with report-only mode:</strong></p><p>CSP implementation is challenging because every external resource — including analytics, CDNs, and custom fonts — must be explicitly whitelisted. To prevent unexpected site breakage, begin with Content-Security-Policy-Report-Only. This directive audits and logs policy violations without blocking resources, giving you visibility into potential issues before enabling strict enforcement.</p><p><strong>Header 2 — X-Frame-Options:</strong></p><p>This header prevents external domains from embedding your application inside an iframe, protecting users against clickjacking attacks where hidden UI overlays trick them into executing unintended actions.</p><ul><li><strong>X-Frame-Options: DENY</strong>: Completely blocks any domain from framing your site.</li><li><strong>X-Frame-Options: SAMEORIGIN</strong>: Restricts framing exclusively to your own origin.</li></ul><p>While CSP’s frame-ancestors directive serves as the modern replacement (and overrides X-Frame-Options in current browsers), you should retain X-Frame-Options to maintain backward compatibility with legacy clients. Note that this header applies only to HTML documents and provides no meaningful security for API payloads or redirects.</p><p><strong>Header 3 — X-Content-Type-Options:</strong></p><p>The X-Content-Type-Options: nosniff header disables browser &quot;MIME sniffing&quot;—a feature where browsers ignore the server&#39;s declared Content-Type and infer file types based on the response payload. Without this directive, an attacker who uploads a malicious file could trick the browser into executing plain text or user-generated media as executable JavaScript. Enforcing nosniff compels the browser to strictly honor the server&#39;s specified Content-Type.</p><p><strong>Header 4 — Strict-Transport-Security:</strong></p><p>HTTP Strict Transport Security (HSTS) enforces HTTPS-only connections for your domain, automatically upgrading unencrypted http:// requests or link clicks before they leave the browser. Without HSTS, a man-in-the-middle attacker can intercept that initial HTTP request before a server redirect occurs, compromising sensitive cookies and session tokens.</p><pre>Strict-Transport-Security: max-age=31536000; includeSubDomains</pre><h3>Directives Breakdown</h3><ul><li><strong>max-age=31536000</strong>: Directs the browser to cache and enforce this rule for 1 year (31,536,000 seconds).</li><li><strong>includeSubDomains</strong>: Extends the HTTPS requirement across all current and future subdomains.</li></ul><blockquote><em>⚠️ </em><strong><em>Critical Pre-deployment Warning</em></strong></blockquote><blockquote><em>HSTS is a client-side policy, not a server config or SSL certificate fix. </em><strong><em>Your site and subdomains must be 100% compliant with HTTPS before enabling this header.</em></strong><em> Injecting HSTS while serving unencrypted HTTP assets will render those resources unreachable for the full </em><em>max-age duration.</em></blockquote><h3>Understanding the preload Flag</h3><p>Adding preload submits your domain to global browser preload lists built into Chrome, Firefox, Safari, and Edge. This forces <em>first-time ever</em> connections over HTTPS before the browser even receives its initial response header. Because removal from browser preload lists takes months, treat preload as an irreversible operational decision rather than a routine copy-paste flag.</p><p><strong>Header 5 — Referrer-Policy:</strong></p><p>When a user follows an outbound link, the browser sends a Referer header revealing the source URL. This risks leaking sensitive path details, such as user IDs or session tokens, to external domains.</p><pre>Referrer-Policy: strict-origin-when-cross-origin</pre><p>This default-recommended policy passes full URLs to same-origin destinations, but strips path data down to the domain origin for external requests — preventing sensitive parameters from leaking outside your site.</p><ul><li><strong>Key Policy Alternatives:</strong></li><li><strong>no-referrer</strong>: Suppresses referrer data completely for all requests.</li><li><strong>same-origin</strong>: Transmits referrer data only for internal, same-origin requests.</li><li><strong>strict-origin</strong>: Transmits only the domain origin for all requests, omitting full paths entirely.</li></ul><p><strong>Permissions-Policy (Formerly Feature-Policy)</strong></p><p>Permissions-Policy restricts which browser hardware and API capabilities—such as the camera, microphone, location tracking, or payment interfaces—your web app can access. Disabling unused capabilities minimizes the overall attack surface if a client-side vulnerability occurs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79569370d91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Find and Fix Slow Queries in Laravel Database?]]></title>
            <link>https://medium.com/@talhaouimouad04/how-to-find-and-fix-slow-queries-in-laravel-database-89e42222b132?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e42222b132</guid>
            <category><![CDATA[somfony]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[elequant]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 14:26:02 GMT</pubDate>
            <atom:updated>2026-08-18T14:26:02.944Z</atom:updated>
            <content:encoded><![CDATA[<p>The first time I noticed a Laravel application slowing down, my first instinct was to inspect the PHP code. The routes were functioning correctly, and there were no obvious errors, yet some requests were taking noticeably longer than expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHwexARGtLAQz9o8fIlTQw.jpeg" /><figcaption>laravel performance</figcaption></figure><p>After investigating the application more closely, I discovered that the database was handling far more work than it needed to. Some queries were scanning large numbers of rows, certain columns lacked proper indexes, and a few pages were running identical queries multiple times.</p><p>That experience changed the way I approach performance issues in Laravel. Rather than guessing what might be causing the slowdown, I start by measuring the database queries, identifying the most expensive ones, and then investigating why they are being executed inefficiently.</p><p><strong>Find the Slow Queries :</strong></p><p>Before modifying any query, I prefer to have clear evidence that it is actually contributing to the performance issue. Laravel’s built-in query logging can be very useful for monitoring and analyzing queries during development and debugging.</p><pre>DB::enableQueryLog();<br><br>$queries = DB::getQueryLog();</pre><p>This gives me a clear view of the SQL queries executed during a specific part of the application, making it easier to identify unnecessary or repeated queries, as well as queries retrieving more data than the page actually needs. However, I avoid keeping query logging enabled throughout a production environment, especially on busy applications, because it is primarily a debugging and troubleshooting tool rather than something that should be enabled indiscriminately.</p><p><strong>Laravel Debugging Tools :</strong></p><p>Laravel Debugbar is another helpful tool during development. It provides a convenient way to monitor database activity while working on a page, making it easier to spot repeated queries and identify other patterns that could be affecting application performance.</p><pre>composer require barryvdh/laravel-debugbar — dev</pre><p>The key isn’t just adding a debugging tool to your Laravel project. What really matters is analyzing the information it provides and understanding why the application is generating those queries in the first place.</p><p><strong>The N+1 Query Problem:</strong></p><p>One issue I always watch for in Laravel applications is the <strong>N+1 query problem</strong>. For instance, you might fetch a list of users and then query each user’s orders separately inside a loop. This can lead to one query for the users followed by an additional query for every user’s orders. While this might not be noticeable with a small amount of data, it can quickly become a serious performance problem when working with hundreds or thousands of records.</p><pre>$users = User::with(‘orders’)-&gt;get();</pre><p>Eager loading can reduce this unnecessary database activity by loading related records more efficiently.</p><p><strong>Retrieve just the needed data:</strong></p><p>I have also learned to avoid retrieving entire records when an application only needs a few columns.</p><pre>$users = User::select(‘id’, ‘name’)-&gt;get();</pre><p>Selecting only the columns your application actually needs can help reduce memory consumption and minimize the amount of data transferred between the database and your Laravel application.</p><p><strong>Pagination for Large Datasets:</strong></p><p>Fetching thousands of records in a single Laravel response is usually not a good approach. Pagination helps control the amount of data the application processes and sends back at once. For example, you can retrieve 25 users per page with User::paginate(25). When dealing with very large datasets or background jobs, Laravel’s chunking and lazy collection features can also help process records more efficiently without loading everything into memory at once.</p><p><strong>Check Your Database Indexes :</strong></p><p>One of the most significant database performance improvements I’ve encountered has come from using indexes correctly. When an application frequently filters or searches by columns such as email, account_number, status, or created_at, adding an appropriate index can significantly speed up those queries.</p><pre>$table-&gt;index(&#39;status&#39;);<br><br>$table-&gt;unique(&#39;email&#39;);</pre><p>However, indexes shouldn’t be added without considering the application’s actual query patterns. While they can make read operations much faster, they also require additional storage and can increase the cost of INSERT and UPDATE operations. The best indexing strategy depends on how the database is being used and which queries are executed most frequently.</p><p><strong>Understanding Database using the EXPLAIN:</strong></p><p>When I come across a query that seems inefficient, I want to understand how the database intends to execute it. This is where EXPLAIN becomes particularly useful.</p><pre>EXPLAIN SELECT * FROM users WHERE email = &#39;example@example.com&#39;;</pre><p>The output varies depending on the database engine, but EXPLAIN can provide valuable details about the execution plan, including which indexes are being used and how many rows are examined. If a query ends up scanning a large table instead of using an expected index, that’s a strong indication that the query or database structure needs further investigation.</p><p><strong>Watch Out for Queries Inside Loops:</strong></p><p>Database queries placed inside application loops can quickly become a performance problem, turning a simple task into hundreds of separate database requests. Whenever I notice a query running inside a loop, I consider whether the required data could be fetched once, eager-loaded, grouped, or retrieved using a more efficient approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e42222b132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New Feature in PHP 8.6]]></title>
            <link>https://medium.com/@talhaouimouad04/new-feature-in-php-8-6-c06be704642c?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c06be704642c</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[somfony]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[php-developers]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 08:00:47 GMT</pubDate>
            <atom:updated>2026-08-25T14:39:12.154Z</atom:updated>
            <content:encoded><![CDATA[<p>PHP 8.6 will be released on November 19, 2026. It includes partial function application, a new polling API, function parameter doc comments, a bunch of deprecations, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYZgrZAT5DjqfBJ1AnyFxw.png" /><figcaption>php 8.6</figcaption></figure><p><strong>1- Partial function application (PFA):</strong></p><p>Allows you to create a reference to a closure with some of its parameters prefilled. A simple example is below:</p><pre>$makeSlug = str_replace(&#39; &#39;, &#39;-&#39;, ?);</pre><p>Once a closure is created, you can use it like this:</p><pre>$makeSlug(&#39;Hello World&#39;);<br><br>// Hello-World</pre><p>PFA is especially useful when combined with the pipe operator, because the pipe operator always requires a callable with exactly one parameter.</p><pre>$output = &#39;Hello World&#39; <br>    |&gt; str_replace(&#39; &#39;, &#39;-&#39;, ?)<br>    |&gt; strtolower(...);<br><br>// hello-world</pre><p><strong>2- Readonly property defaults:</strong></p><p>With the addition of property hooks in PHP 8.4, you can define property hooks on interfaces:</p><pre>interface MigratesUp<br>{<br>    public string $name { get; }<br><br>    public function up(): QueryStatement;<br>}</pre><p>Because of this change, though, readonly properties with default values would make sense in many cases:</p><pre>final class CreateBooksTable implements MigratesUp<br>{<br>    public readonly string $name = &#39;2026-01-01_create_books_table&#39;;<br>    <br>    public function up(): QueryStatement<br>    { /* … */ }<br>}</pre><p>Before PHP 8.6, readonly properties could not have default values. This was an intentional design decision when readonly properties were first introduced, since a readonly property with a predefined value is essentially equivalent to a constant.</p><p>However, this limitation made more sense at the time, before property hooks could be declared in interfaces. With property hooks now supported in interfaces, having a default, immutable value can be useful when it forms part of a broader contract.</p><p>For this reason, PHP 8.6 now allows readonly properties to have default values.</p><pre>final class CreateBooksTable implements MigratesUp<br>{<br>    // ✅<br>    public readonly string $name = &#39;2026-01-01_create_books_table&#39;;<br>    <br>    // …<br>}</pre><h4><strong>3- Polling API:</strong></h4><p>The new Polling API was created first and foremost to facilitate easier internal dev, it is exposed to userland, which could lead to lower-level frameworks like ReactPHP or AMp to make use of them:</p><pre>use Io\Poll\Context;<br>use Io\Poll\Event;<br>use Io\Poll\StreamPollHandle;<br>use Time\Duration;<br> <br>// Create a poll context with automatic backend selection<br>$context = new Context();<br><br>// Create a non-blocking socket, just like before<br>$stream = stream_socket_server(&#39;tcp://0.0.0.0:8080&#39;, $errno, $errstr);<br>stream_set_blocking($stream, false);<br><br>// Wrap that stream in a new `StreamPollHandle` so that it can make use of the new API<br>$handle = new StreamPollHandle($stream);<br> <br>// Add the handle to the context<br>$context-&gt;add($handle, [Event::Read], [&#39;type&#39; =&gt; &#39;server&#39;]);<br><br>while (true) {<br>    // Wait for one second, polling for new events<br>    $watchers = $context-&gt;wait(new Duration::fromSeconds(1));<br>    <br>    // …<br>}</pre><p>It’s important to note that this new polling API won’t introduce any new async features to PHP. It’s another (and easier) way to interact with async features — previously PHP only had stream_select() as an option for I/O multiplexing. Because the new API also works with several backends when available, like epoll or WSAPoll, performance will be better compared to stream_select() at a certain scale.</p><p>The new polling API also doesn’t come with a built-in event loop, so wrapping it into a higher-level abstraction is still up to userland libraries.</p><h4><strong>4 - The New duration class:</strong></h4><p>The \Time\Duration class was added to represent a duration of time:</p><pre>use Time\Duration;<br>sleep(Duration::fromMilliseconds(500));</pre><p>The class also comes with some other methods to do mathematical operations with durations:</p><pre>$baseDelay = Duration::fromMilliseconds(100);<br>$baseDelay-&gt;add(Duration::fromSeconds(2));<br>$attempt = 5;<br>$delay = $baseDelay-&gt;multiplyBy(2**$attempt);</pre><p>We can also use it for comparison:</p><pre>if ($durationA &lt; $durationB){<br><br>}</pre><p>And you’ll be able to use it in places like the new polling API:</p><pre>$watchers = $context-&gt;wait(new Duration::fromSeconds(1));</pre><p><strong>5- A new clamp function:</strong></p><p>clamp() is a pretty common function in many frameworks already, which will now ship built-in with PHP 8.6. This function ensures a given value (numeric or other) is within a given bound. If not, the nearest edge value is returned.</p><pre>clamp(10, min: 0, max: 100); // Will return `10`<br>clamp(101, min: 0, max: 100); // Will return `100`<br>clamp(-1, min: 0, max: 100); // Will return `0`</pre><p>clamp() works on more than integers. For example, strings:</p><pre>clamp(&quot;y&quot;, &quot;x&quot;, &quot;z&quot;) // Will return &quot;y&quot;<br>clamp(&quot;a&quot;, &quot;x&quot;, &quot;z&quot;) // Will return &quot;x&quot;</pre><p>Or DateTime objects:</p><pre>clamp(<br>    value: new DateTimeImmutable(&#39;2025-01-01&#39;), <br>    min: new DateTimeImmutable(&#39;2026-01-01&#39;), <br>    max: new DateTimeImmutable(&#39;2026-12-31&#39;),<br>); // Will return `DateTimeImmutable(&#39;2026-01-01&#39;)`</pre><p>If you find this information helpful, consider supporting my work with a coffee: <a href="https://buymeacoffee.com/talhaouimou">Buy Me a Coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c06be704642c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collectors teeing java]]></title>
            <link>https://medium.com/@talhaouimouad04/collectors-teeing-java-b3c66fbf08cb?source=rss-333bd8fc8ddc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c66fbf08cb</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java25]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[stream]]></category>
            <dc:creator><![CDATA[Talhaoui mouad]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 17:06:51 GMT</pubDate>
            <atom:updated>2026-08-01T17:06:51.385Z</atom:updated>
            <content:encoded><![CDATA[<p>In Java 12, within the java.util.stream.Collectors class, a static method was introduced that allows you to perform two separate collection operations on a single stream simultaneously and then merge their results. It eliminates the need to iterate through a stream twice or buffer data into memory when working with single-pass data sources like I/O streams, which was named teeing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*n-HKnm06r7WCAGXm1pprHw.png" /><figcaption>Collectors teeing java</figcaption></figure><p><strong>Process:</strong></p><p>The term “teeing” comes from command-line processing (the tee command) or a T-shaped pipe split. It splits the incoming stream elements into two distinct “downstream” collectors. Once both collectors finish processing, a merger function combines their respective outputs into a single final result.</p><p><strong>Examples:</strong></p><p><strong>1- Calculating Sum and Average Simultaneously:</strong></p><p>A classic use case is extracting multiple statistical metrics from a stream of numbers without iterating twice.</p><pre>import java.util.List;<br>import java.util.stream.Collectors;<br><br>public class TeeingExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(10, 20, 30, 40, 50);<br><br>        String result = numbers.stream().collect(<br>            Collectors.teeing(<br>                Collectors.summingInt(Integer::intValue),    // First collector<br>                Collectors.averagingInt(Integer::intValue), // Second collector<br>                (sum, avg) -&gt; &quot;Sum: &quot; + sum + &quot;, Average: &quot; + avg // Merger function<br>            )<br>        );<br><br>        System.out.println(result); // Output: Sum: 150, Average: 30.0<br>    }<br>}</pre><p><strong>2. Filtering Data into Separate Lists:</strong></p><p>You can also use it to partition your data into two customized datasets within a single pass.</p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br><br>public class TeeingFilterExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);<br><br>        Map&lt;String, List&lt;Integer&gt;&gt; partitioned = numbers.stream().collect(<br>            Collectors.teeing(<br>                Collectors.filtering(n -&gt; n % 2 == 0, Collectors.toList()), // Evens<br>                Collectors.filtering(n -&gt; n % 2 != 0, Collectors.toList()), // Odds<br>                (evens, odds) -&gt; Map.of(&quot;Evens&quot;, evens, &quot;Odds&quot;, odds)       // Combine into Map<br>            )<br>        );<br><br>        System.out.println(partitioned); // Output: {Odds=[1, 3, 5, 7, 9], Evens=[2, 4, 6, 8, 10]}<br>    }<br>}</pre><p><strong>Advantages of Teeing:</strong></p><p><strong>1-Single-Pass Efficiency:</strong></p><p>It evaluates elements as they pass by, avoiding the overhead of re-streaming or running multiple loops over large datasets.</p><p><strong>2-Memory Savings:</strong></p><p>Essential for non-repeatable or heavy I\O data streams where you cannot afford to cache everything into an in-memory collection first.</p><p><strong>3-Readability:</strong></p><p>Keeps complex multi-aggregation stream queries inside a concise, declarative structure instead of breaking them into fragmented variables.</p><p>If you find this information helpful, consider supporting my work with a coffee: <a href="https://buymeacoffee.com/talhaouimou">Buy Me a Coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c66fbf08cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>