<?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 PixelKK on Medium]]></title>
        <description><![CDATA[Stories by PixelKK on Medium]]></description>
        <link>https://medium.com/@PixelKK?source=rss-f07f7b3d3e91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IJnTn6k-ZPoope-zm_5Ngg.png</url>
            <title>Stories by PixelKK on Medium</title>
            <link>https://medium.com/@PixelKK?source=rss-f07f7b3d3e91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:45:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@PixelKK/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[What are we teaching kids to do with screens?]]></title>
            <link>https://medium.com/@PixelKK/what-are-we-teaching-kids-to-do-with-screens-95bab742eb10?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/95bab742eb10</guid>
            <category><![CDATA[parenting]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[child-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[psychology]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 22:11:01 GMT</pubDate>
            <atom:updated>2026-10-05T07:29:46.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yq74SxfN1c6RCEC-v6gIpw.jpeg" /></figure><p><strong>I grew up with screens.</strong></p><p>Video games, computers, television, the early internet. I don’t remember anyone having serious conversations about “screen time” when I was a kid. There simply wasn’t enough technology around for it to become the parenting question it is today.</p><p>Now, it is almost impossible to avoid. Children use screens at school, at home, to talk to friends, to play games, to watch videos, to learn things and, increasingly, to create things. And yet, when we talk about children and technology, the conversation often seems to come back to the same question: how much screen time is too much?</p><p>I understand why. Sleep, physical activity, play and time away from devices all matter, particularly for younger children. The World Health Organization recommends no sedentary screen time for one-year-olds and no more than one hour a day for children aged two to four, with less being better. Those recommendations make sense to me.</p><p>But as children get older, I’m increasingly uncomfortable with treating “screen time” as one giant category. Because an hour spent doing something on a screen isn’t necessarily the same experience as another hour spent doing something on a screen.</p><p><strong>Not all screen time is the same.</strong></p><p>Imagine two children spending an hour in front of a tablet.</p><p>One watches an endless stream of short videos, moving from one piece of content to the next until something else finally interrupts the feed. The other watches <em>Prehistoric Planet</em> because they are currently obsessed with dinosaurs. They start asking why some dinosaurs had feathers, what the Earth looked like millions of years ago, how ecosystems worked and whether the animals they are seeing really existed.</p><p>Both children have technically spent an hour looking at a screen. I’m not convinced they have had the same experience.</p><p>This isn’t just a philosophical distinction. Research increasingly suggests that the context of screen use matters, particularly for younger children. A 2024 systematic review and meta-analysis published in <em>JAMA Pediatrics</em>, covering 100 studies and more than 176,000 children under six, found different associations depending on how screens were being used. Program viewing and background television were associated with poorer cognitive outcomes, while co-use with caregivers was associated with better outcomes. The researchers emphasized that content, context and the way screens are used matter alongside duration.</p><p>That doesn’t mean that watching a documentary automatically makes screen time “good”, or that every educational app is beneficial. It simply makes the idea of one single number for all screen use seem a little too simplistic.</p><p>There is a difference between consuming, learning and creating, even if all three happen on the same device.</p><p><strong>I grew up with video games too.</strong></p><p>I grew up playing Mario, and looking back, there is something educational or at least beneficial in playing this style of game. You miss a jump, lose a life, try again, understand the level a little better and eventually get further. Failure and frustration are part of the game rather than the end of it, and progress comes from figuring out what to do differently.</p><p>That’s my personal experience of playing those games, not a scientific claim about what Mario does to children’s brains. But I think the structure of that loop encourages perseverance and learning by trial and error.</p><p>I’ve also played some of the games released more recently, such as Brawl Stars. It was a very different experience. The matches were short, the feedback was immediate, there was always something to unlock and another progression level to reach. Whether you won or lost, another match was only a few seconds away, and there was always a reason to keep playing.</p><p>Eventually, I stopped because the whole thing became repetitive for me. Maybe that’s partly because I’m older. Maybe I’ve just become less sensitive to those particular loops. Whatever the reason, it made me think about something I hadn’t really considered when I was younger: what exactly are we rewarding?</p><p>Modern games are incredibly good at creating feedback loops. Points, levels, badges, unlocks, streaks, challenges and rewards can all make an activity more engaging. Gamification itself isn’t inherently good or bad. What matters is what behaviour the system is designed to reinforce.</p><p><strong>What exactly are we rewarding?</strong></p><p>This is where things get interesting for children.</p><p>We already use reward systems everywhere. Video games use them. Fitness apps use them. Language-learning apps use them. Loyalty programs use them. Even adults are perfectly happy to collect points for buying coffee they were probably going to buy anyway.</p><p>So I don’t think the question is whether children should ever encounter rewards. They already do.</p><p>The more interesting question is what those rewards are encouraging them to do.</p><p>For example, researchers Deci, Koestner and Ryan looked at 128 studies on rewards and motivation. Their findings suggest that rewards can sometimes have an unexpected effect: if you reward someone for doing something they already enjoy, they can start to feel that they are doing it for the reward rather than because they actually want to do it.</p><p>Imagine a child who loves drawing. If you start giving them a prize every time they draw, the prize can slowly become part of the reason they draw. Take the prize away, and the activity may feel less interesting than it did before, and motivation decreases.</p><p>That doesn’t mean rewards are bad.</p><p>It means <strong>how you use them matters</strong>.</p><p>There is a big difference between saying, “You love drawing, so I’ll give you something every time you do it,” and saying, “You’ve finished the things you needed to do today, and now you can choose how to use the points you earned.”</p><p>The first one risks putting a price on something the child already enjoys. The second is more about <a href="https://groowble.com/creating-shared-rules-and-rewards-your-kids-understand/">making effort and progress visible</a>.</p><p>That distinction is important when we start talking about children, chores and screen time.</p><h3>Maybe we should reward effort, not just compliance</h3><p>This distinction becomes particularly interesting when we talk about screen time.</p><p>I’m not convinced children should have to earn every enjoyable thing they do. If a child wants to spend an afternoon learning how to code, researching sharks, watching a documentary about dinosaurs or creating a video game, I don’t see much value in saying, “First you need to complete three chores to unlock your educational screen time.”</p><p>We’ve actually been doing something like this at home for a while. With the oldest, we’ve been using AI to build a video game together. He comes up with ideas, we talk about how the game should work, we try things, break things, fix them and gradually turn an idea into something playable.</p><p>Technically, we’re spending time in front of a screen. But I don’t count that time as part of his screen-time allowance. Because the activity itself is fundamentally different from sitting down and consuming whatever an algorithm happens to put in front of you.</p><p>He’s creating something, making decisions and discovering how software works. He also gets to discover that his brilliant idea doesn’t work at all, which is probably one of the more useful parts of the experience.</p><p>That’s why I find the idea of treating all screen time as one big number increasingly difficult. If a child spends an hour watching random short videos, that’s one thing. If they spend an hour trying to figure out why the character they just created can’t jump, I’m not sure I’d want to put those two hours in exactly the same category. Even certain video games such as Minecraft involve creativity and problem-solving, while others, such as Brawl Stars, are primarily designed around competition, progression and short feedback loops.</p><h3>How Groowble changed our daily routines</h3><p>This thinking is also what led us to build <a href="https://groowble.com/">Groowble</a>, but the reason we built it is actually much more practical than all of this might make it sound.</p><p>At home, one of the things we wanted to change was the amount of negotiation around everyday routines. The morning was a good example. <a href="https://groowble.com/age-appropriate-chores-for-kids/">Getting up, getting dressed, having breakfast, brushing teeth, getting the school bag ready</a> and actually leaving the house can somehow become a surprisingly complicated sequence when every step turns into a discussion.</p><p>So we created a morning routine with clear tasks. Not because we wanted to turn the morning into a military operation, but because we realised that everyone was spending too much energy negotiating things that were going to happen anyway.</p><p>The same thing happens after school. Come home, put your clothes in the laundry, put your things away, do homework before getting distracted by something else, and then move on to whatever comes next. Once these things are part of a routine, there is much less need for an adult to constantly remind someone what they should be doing.</p><p>And, at least in our case, it works.</p><p>What surprised me was that the biggest change wasn’t actually about getting more chores done. It was the change in the conversations around them. Before, a lot of the negotiation was about screen time, Roblox and whatever reward was most exciting at that particular moment. Now, there are other things to work towards.</p><p>Sometimes the reward is still screen time. There’s nothing wrong with that. But it can also be something completely different, like being allowed to stay up a little later at the weekend to watch a movie together, or having enough time for one of those ridiculously long board games that somehow never seems to end. We’ve played Munchkin sessions that felt like they were going to outlive us.</p><p>The point isn’t that one reward is better than another. It’s that the child has something to work towards, and the reward doesn’t always have to be another hour in front of a screen.</p><p>That’s also why we don’t really think of Groowble as an app for “rewarding chores”. The chores are just one part of the system. What we’re really trying to make visible is effort, consistency and progress.</p><p>A child does something that contributes to the household. They see that effort turn into points. Those points give them choices, and sometimes that choice is a reward they wouldn’t have thought about asking for in the first place.</p><p>The basic idea is simple: <strong>effort leads to progress, progress leads to points, points create choice, and choice can lead to a reward.</strong></p><p>But the reward isn’t the whole point.</p><p>That distinction has also changed the way we think about screen time ourselves. If a child wants to spend an afternoon creating a game, learning how to code or watching something because they’re genuinely interested in it, I don’t see much value in making them earn that time through chores first.</p><p>Entertainment can be a reward. <strong>Curiosity shouldn’t have to be.</strong></p><h3>So what should we actually be asking?</h3><p>Maybe “How much screen time?” is still a useful question, especially for younger children. But as children grow, I think we need a few more questions alongside it.</p><p>What are they watching? What are they playing? Are they consuming or creating? Who are they interacting with? What is the screen replacing? Are they learning something, making something or simply being pulled from one piece of content to the next?</p><p>The answer won’t always be obvious, and I don’t think it needs to be.</p><p>Screens are going to be part of our children’s lives whether we like it or not. Trying to remove them completely doesn’t seem particularly realistic. What we can do is help children understand that a screen isn’t just something that gives them entertainment. It can also be a tool for creating, learning, exploring, communicating and building things. We can also help them develop healthy habits around games and social media, by setting reasonable limits and helping them practice stopping when it’s time to disconnect.</p><p>And outside the screen, the same principle applies. Children can learn that effort leads to progress, that progress creates choices, and that choices have consequences.</p><p>That doesn’t mean every chore needs a prize. It doesn’t mean children should have to earn every enjoyable activity. And it certainly doesn’t mean turning family life into a giant points system.</p><p>It means making progress more visible and increasing their motivation to take on new tasks and to make an effort.</p><p>Maybe that’s a more useful question than simply asking how many hours a child spent looking at a screen:</p><p><strong>What are we teaching them to do with it?</strong></p><h3>References</h3><p><strong>World Health Organization, 2019</strong><br> <em>Guidelines on physical activity, sedentary behaviour and sleep for children under 5 years of age.</em><br> <a href="https://www.who.int/publications/i/item/9789241550536?utm_source=chatgpt.com">WHO guidelines</a></p><p><strong>JAMA Pediatrics, 2024</strong><br> <em>Early Childhood Screen Use Contexts and Cognitive and Psychosocial Outcomes: A Systematic Review and Meta-analysis.</em><br> 100 studies, 176,742 participants.<br> <a href="https://jamanetwork.com/journals/jamapediatrics/fullarticle/2821940?utm_source=chatgpt.com">JAMA Pediatrics study</a></p><p><strong>Deci, Koestner &amp; Ryan, 1999</strong><br> <em>A Meta-Analytic Review of Experiments Examining the Effects of Extrinsic Rewards on Intrinsic Motivation.</em><br> <a href="https://pubmed.ncbi.nlm.nih.gov/10589297/?utm_source=chatgpt.com">PubMed reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95bab742eb10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I run a production app alone. AI made me a plausible team.]]></title>
            <link>https://medium.com/@PixelKK/i-run-a-production-app-alone-ai-made-me-a-plausible-team-46ddf359f579?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/46ddf359f579</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[indie-hacking]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 07:41:57 GMT</pubDate>
            <atom:updated>2026-08-12T07:41:57.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZdbhksfwkH1OK7JvU3LrQ.jpeg" /></figure><p><em>90,000 lines of code, four languages, iOS and Android, and roughly half my commits co-authored by Claude.</em></p><p>Every article about AI-assisted development seems to end at the same place: a prototype. Someone builds a to do app in an afternoon, writes “the future is here,” and moves on.</p><p>Nobody talks about month eight.</p><p>Month eight is when you have a real user base, an installed app you can’t break, four languages to maintain, App Store reviews to answer, and an API where deleting a field is forbidden because some kid’s tablet in another country still depends on it.</p><p>I know, because I’m there. <a href="https://groowble.com/">**Groowble</a> is a family chore app: parents create missions, routines and tasks, kids earn points by doing their tasks and earn points, which become rewards.** It’s available on the <a href="https://apps.apple.com/app/id6756936452">App Store</a> and <a href="https://play.google.com/store/apps/details?id=com.groowble.app">Google Play</a> in English, French, Spanish and Arabic. Under the hood: a Laravel 12 API, and an Expo/React Native app with custom Swift and Kotlin modules for iOS Live Activities and Android widgets.</p><p>And on the engineering side, I’m alone. Groowble itself isn’t a one-person company. My co-founder, Collette Brown, owns everything marketing: positioning, the website, the App Store presence, user acquisition. A front-end developer also helped get the app off the ground in the early days before I picked up the torch. But today, every line of code, every migration, every release, every 2 a.m. infrastructure decision: one developer.</p><p>This is not a “look how fast AI made me” article. It’s an honest breakdown of what it actually takes to run a production app solo with an AI pair: what worked, what the AI is genuinely bad at, and why the real leverage wasn’t code generation at all.</p><h3>What is Groowble, exactly?</h3><p>The app was born from a scene every parent knows. Screen time ends, and the negotiation starts: whining, bargaining, one more game, five more minutes, anything to keep playing. Hold the line and you’re the villain. Give in and you’ve just taught them that whining works.</p><p>So for readers landing here first: <strong>Groowble is a family chore and rewards app that makes effort the only currency for what kids want.</strong> Parents create missions and challenges (chores, homework, routines) and set their point value. Kids complete them, earn points, and trade them for rewards the family agreed on upfront: extra screen time, individual treats, or a shared “family pot” where siblings save toward a common goal together. Timed chores run as an iOS Live Activity or an Android ongoing notification, and parents can validate a task straight from the home-screen widget. Everything syncs across the family’s devices in real time.</p><p>The effect on real kids was almost immediate. When the timer runs out, the only negotiation lever left is other chores: <em>“Can I have 30 more minutes? I’ll empty the dishwasher.”</em> Then comes the part we didn’t expect. Once other rewards enter the system, kids start showing up spontaneously, asking how they can earn more points. The whining turns into initiative. That’s the virtuous circle the whole app is built around.</p><ul><li><strong>Platforms</strong>: iOS and Android, phone and tablet (<a href="https://groowble.com/">groowble.com</a>)</li><li><strong>Languages</strong>: English, French, Spanish, Arabic</li><li><strong>Rating</strong>: 5 stars from the Educational App Store</li><li><strong>Promise</strong>: “Grow good habits, playfully.” Positive reinforcement instead of nagging.</li></ul><p>That’s the product. Now for how one developer keeps it alive.</p><h3>The scale we’re talking about</h3><p>“Solo dev with AI” means nothing without a sense of scale, so here are the only numbers that matter. The repos total about 90,000 lines of code: 52 screens and 7 custom native modules in Swift and Kotlin on the app, 29 models and 878 PHPUnit tests on the backend, all of it shipping in four languages. And roughly 40% of backend commits and 55% of app commits are co-authored by Claude.</p><p>One developer.</p><p>The question isn’t whether AI can write code (it obviously can). The question is: <strong>how does one person keep all of this coherent?</strong></p><p>After eight months, my answer comes down to three problems. <strong>Consistency</strong>: how do you stop the AI from slowly eroding your architecture? <strong>Memory</strong>: how do you stop it from forgetting everything it learned yesterday? <strong>Review</strong>: who challenges your work when you’re alone? Everything that follows is the system I built to answer them.</p><h3>Problem #1: the AI will slowly erode your architecture</h3><p>If you’ve read <a href="https://medium.com/@PixelKK/we-benchmarked-claude-md-on-a-real-production-laravel-project-heres-what-actually-matters-a9185b54bd4b">my CLAUDE.md benchmark</a>, you know I’m skeptical of giant context files. What I’ve landed on for Groowble is different: my CLAUDE.md files don’t describe the codebase. <strong>They describe the decisions that are not up for renegotiation.</strong></p><p>Three files, roughly a thousand lines total, and they read less like documentation and more like law:</p><ul><li>Repository Pattern everywhere: Model::query() is forbidden outside repositories</li><li>Every business action fires an event, named in the past tense, side effects only in listeners</li><li>The API is <strong>additive-only</strong>: you never delete or rename a field, ever</li><li>On the app: React Native’s &lt;Text&gt; is banned (a Typography component only), no hardcoded colors or spacing (design tokens only), no let, no for loops, no any</li><li>PHPUnit only. No Pest. Non-negotiable.</li><li>etc …</li></ul><p>Here’s the part that surprised me: <strong>strict conventions matter more with AI, not less.</strong></p><p>A human teammate absorbs your codebase’s culture over months. An AI model starts fresh every session. The only culture it gets is the one you wrote down. Loose conventions that a human team survives through tribal knowledge become chaos when your “team” has no memory of yesterday.</p><p>So the constraint budget flipped. Rules I might have considered pedantic on a human team (“components never define external margins,” “class names reflect business intent”) became the cheapest quality lever I have. The model reads them at the start of every single session and applies them with a consistency no tired human ever matches.</p><p>One real example of how a rule gets born:</p><blockquote><strong><em>The AI’s move:</em></strong><em> while touching a small component, run the code formatter in write mode on the whole repo, to clean things up.</em></blockquote><blockquote><strong><em>Why it was wrong:</em></strong><em> about 48 unrelated files got reformatted, and the actual fix drowned in a diff no one could review.</em></blockquote><blockquote><strong><em>The correction:</em></strong><em> one more line of law. Formatters and linters run on touched files only.</em></blockquote><p>The codebase enforces the rest. PHPStan level 5, strict TypeScript, and a linter opinionated enough that “it compiles and passes static analysis” already means something.</p><h3>Problem #2: the AI forgets everything, every day</h3><p>The dirty secret of AI-assisted development: <strong>your assistant has amnesia.</strong> Every session starts at zero. Whatever context you don’t persist, you will re-explain. Or worse: the AI will re-discover it wrong.</p><p>Here’s what “re-discover it wrong” looks like in practice:</p><blockquote><strong><em>The AI’s diagnosis:</em></strong><em> “this method always returns </em><em>false. That&#39;s a bug.&quot; Followed by a confident fix.</em></blockquote><blockquote><strong><em>Why it was wrong:</em></strong><em> the feature behind that method was intentionally disabled, not broken. With an installed app base you can’t just delete code (old app versions still send and read those fields), so features get neutralized at a single point instead. To a fresh session, a deliberate kill switch is indistinguishable from a regression.</em></blockquote><blockquote><strong><em>The correction:</em></strong><em> a registry of disabled-but-not-deleted features. Each entry documents the neutralization point, the cascade effects, and the condition for safe deletion, expressed as a minimum supported app version. It’s read </em>before<em> concluding anything is broken.</em></blockquote><p>The second memory document is <strong>an analytics catalog</strong>: every event, its trigger, its params, and the file that emits it, updated in the same pass as the code. It also records hard-won platform knowledge, like the fact that Firebase Analytics doesn’t work inside an iOS app extension, so widget events go through an App Group relay and arrive with delayed timestamps. That sentence cost me days. Now it costs the AI one read.</p><p>Documentation used to be something you wrote for a future colleague who might never come. Now the future colleague shows up every morning with no memory. <strong>Docs stopped being a nice-to-have and became executable context.</strong></p><h3>Problem #3: nobody reviews your work</h3><p>The loneliest part of solo development isn’t writing code. It’s that nobody challenges you.</p><p>No product owner asking “but what happens when the second parent joins the family?” No reviewer noticing your new screen is unusable with VoiceOver. No one reminding you that the feature you just shipped has zero analytics and will be invisible in the data forever.</p><p>My answer was to write the missing roles down as specialized agents. Each one is a markdown file defining a persona, its knowledge, and its checklist. Groowble has eight. The ones that earn their keep:</p><ul><li><strong>product-owner</strong>: turns a raw idea into a structured ticket with acceptance criteria, before any code</li><li><strong>tech-lead</strong>: analyzes and implements across repos; its core instruction is “you don’t re-derive the rules from memory, you open the files”</li><li><strong>accessibility</strong>: carries a dated audit of the entire component library (69 files with unlabeled touchables, ranked by blast radius) and works through it</li><li><strong>analytics-instrumentation</strong>: runs after every feature, because a feature without events is a feature you can’t see</li><li><strong>tablet-design-review</strong>: checks that the tablet layer never degrades the phone experience</li></ul><p>Three of them are mandatory, by rule, at the end of every implementation. That’s the review gate I couldn’t otherwise afford.</p><p>Then there are workflow commands. My /ship command runs documentation, pull request, analytics instrumentation and ticket updates <strong>in parallel</strong>, and finishes by listing the GA4 custom dimensions I have to declare manually in the console, because that&#39;s the step everyone forgets, and forgotten dimensions mean weeks of unreadable data.</p><p>Is this over-engineering for one person? I asked myself that. But these files replaced meetings, not code. They’re the institutional knowledge of a team of one, written down so the AI can play every seat.</p><h3>Four languages, one script, zero translators</h3><p>Groowble ships in English, French, Spanish and Arabic: about 1,300 keys per locale on the app, plus Laravel translation files on the backend.</p><p>The workflow: during development, only French and English get written. Then a single make translate command diffs the locales, finds missing keys, batches them, and sends them to an LLM, with a system prompt that embeds the full product brief: what Groowble is, who the personas are, and the tone of voice (&quot;friendly, encouraging, modern, slightly playful, never overly childish&quot;). Spanish comes back as neutral Latin American Spanish, Arabic as Modern Standard Arabic. I review, I commit.</p><p>That’s an entire localization department, replaced by a 15 KB script.</p><h3>Where the AI helps least</h3><p>Fairness requires this section.</p><p><strong>Native code.</strong> Groowble has seven custom native modules: iOS Live Activities for chore timers, Android ongoing notifications, a home-screen widget, App Intents that let a parent validate a task without opening the app. This is where progress slowed to human speed. Not because the AI can’t write Swift or Kotlin, but because the failure feedback loop is brutal: no hot reload, opaque platform constraints, and bugs that only appear on a physical device. The AI proposes; the device disposes.</p><p><strong>Irreversibility.</strong> An AI optimizes for local consistency; it can’t see what can never be undone. My favorite scar:</p><blockquote><strong><em>The AI’s suggestion:</em></strong><em> rename a broadcast event class so the naming stays consistent.</em></blockquote><blockquote><strong><em>Why it was wrong:</em></strong><em> the class name is the wire name. Thousands of installed apps listen for that exact string over WebSockets, and renaming it silently kills real-time sync for every user who hasn’t updated.</em></blockquote><blockquote><strong><em>The correction:</em></strong><em> the four legacy event names are listed in the constitution as untouchable.</em></blockquote><p>That rule got there the hard way. <strong>Judgment about what can never be undone stays firmly on my side of the keyboard.</strong></p><p><strong>Wanting things.</strong> The AI has never once told me a feature was a bad idea for the product. Taste, priorities, and the willingness to say “no, we’re not building that” still get settled the old way, in conversations with my co-founder, not in a chat window.</p><h3>The loop closes</h3><p>My favorite part of the system is the least glamorous: the back office has a page that pulls GA4 data for a period, formats it as markdown, and hands it to an LLM for analysis.</p><p>Which means the loop is now closed. The AI helps write the feature. An agent instruments the feature. And then the AI reads the numbers and tells me whether anyone actually used it.</p><p>One person, with the feedback cycle of a small product team.</p><h3>What actually changed</h3><p>If I had to compress eight months into one lesson: <strong>AI didn’t make me a faster developer. It made me a plausible team.</strong></p><p>Because a solo developer’s real deficit was never typing speed. It’s everything a team provides without anyone noticing: review, memory, consistency, QA, institutional knowledge, someone who challenges your decisions before your users do. That’s what this whole system reproduces, piece by piece: the constitution that keeps 90k lines coherent across sessions, the written-down roles that review my work, the registries that give a memoryless assistant a memory, the pipeline that makes four languages cost the same as two.</p><p>None of that is AI magic. It’s tech-lead work: deciding the rules, writing them down, building the gates. The AI just made that work <em>pay off</em> at a scale where it used to be pointless. <strong>AI isn’t primarily a code generator. It’s an organizational multiplier.</strong> And for the first time, there’s someone on the team who actually reads all the docs.</p><p>Every time. Every session. Without complaining.</p><p><em>**</em><a href="https://groowble.com/"><em>Groowble</em></a><em> is available on the </em><a href="https://apps.apple.com/app/id6756936452"><em>App Store</em></a><em> and </em><a href="https://play.google.com/store/apps/details?id=com.groowble.app"><em>Google Play</em></a><em>. If you have kids and a chore war at home, I’d genuinely love your feedback. And if you’re running a solo project with AI, I’m curious what your setup looks like: tell me in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46ddf359f579" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Benchmarked CLAUDE.md on a Real Production Laravel Project. Here’s What Actually Matters]]></title>
            <link>https://medium.com/@PixelKK/we-benchmarked-claude-md-on-a-real-production-laravel-project-heres-what-actually-matters-a9185b54bd4b?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9185b54bd4b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 16:06:40 GMT</pubDate>
            <atom:updated>2026-02-28T16:06:40.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeNzgPSnS8F_9feG8mJQiQ.png" /><figcaption>What matters: real code over big docs</figcaption></figure><p><em>Spoiler: your codebase is the best context file you’ll ever have.</em></p><p>When I start a new project with Claude CLI, I do what most engineers do.</p><p>I create a big CLAUDE.md.</p><p>I explain the architecture. I document the CQRS separation. I describe the repository layer. I clarify that we use PHPUnit, not Pest. I add Docker commands. I explain the modular structure.</p><p>It feels responsible. It feels like I’m engineering the system properly.</p><p>But recently I started wondering:</p><p><strong>Am I actually improving output quality, or just optimizing my feeling of control?</strong></p><p>So I ran a benchmark.</p><h3>The Context</h3><p>In February 2026, Gloaguen et al. published <a href="https://arxiv.org/abs/2602.11988v1">“Evaluating AGENTS.md” (arXiv:2602.11988v1)</a>.</p><p>Their conclusion: context files increase token consumption by 20%+ with only marginal quality improvements.</p><p>That result bothered me.</p><p>Because in theory, architecture matters. Conventions matter. Layered design matters.</p><p>So I tested it on a real production Laravel application with:</p><ul><li>Modular architecture (Nwidart)</li><li>CQRS separation</li><li>Repository layer</li><li>JSON:API resources</li><li>PHPUnit-only testing</li><li>Docker-based workflow</li><li>Queued listeners</li><li>Strict conventions</li></ul><p>If context files help anywhere, it should be here.</p><h3>The Experiment Design</h3><p>I tested three configurations.</p><h3>Mode A: The Kitchen Sink</h3><ul><li>CLAUDE.md (~1,900 words)</li></ul><p>Nearly 1,900 words explaining every pattern and convention.</p><p>This is what many senior engineers (including me) instinctively create.</p><h3>Mode B: Guardrails Only</h3><ul><li>Root CLAUDE.md (~140 words)</li><li>Only prohibitions and infra commands</li><li>Small CONVENTIONS.md per module (~200 words)</li></ul><p>Minimal but structured.</p><h3>Mode C: Nothing</h3><p>Zero context files.</p><p>The agent explores the codebase and infers everything.</p><h3>Tasks</h3><p>Four standardized tasks:</p><ol><li>CRUD endpoint creation</li><li>N+1 bug diagnosis</li><li>CQRS refactoring</li><li>Queued event listener implementation</li></ol><p>Three runs per condition. 36 runs total. Clean git reset between each. Non-interactive execution. Single evaluator. 7-criteria scoring grid (max 21 points).</p><p>I wanted signal, not anecdotes.</p><h3>The Cost: Context Files Add ~30%</h3><pre>Mode A (Big context)<br>Tokens: 3.2M<br>Tool calls: 61<br><br>Mode B (Guardrails)<br>Tokens: 2.5M<br>Tool calls: 47<br><br>Mode C (Nothing)<br>Tokens: 2.3M<br>Tool calls: 44</pre><p>Mode A consumed about <strong>35% more tokens</strong> than Mode C.</p><p>Mode B cost about 9% more than Mode C.</p><p>The big context file clearly increases agent workload.</p><h3>The Quality: Nearly Identical</h3><pre>Quality Scores (mean ± std)<br><br>CRUD<br>Mode A → 17.7 ± 1.5<br>Mode B → 19.3 ± 0.6  ★<br>Mode C → 18.7 ± 1.5<br><br>N+1 Fix<br>Mode A → 20.6 ± 0.7<br>Mode B → 21.0 ± 0.0  ★<br>Mode C → 21.0 ± 0.0  ★<br><br>CQRS Refactor<br>Mode A → 19.1 ± 1.6<br>Mode B → 20.7 ± 0.6  ★<br>Mode C → 19.6 ± 0.0<br><br>Event Listener<br>Mode A → 18.7 ± 2.0<br>Mode B → 18.7 ± 4.0<br>Mode C → 19.2 ± 1.8  ★<br><br>Average Score<br>Mode A → 19.1<br>Mode B → 19.9  ★<br>Mode C → 19.9  ★</pre><p>Mode B and Mode C produced the same average quality score.</p><p>Mode A, the most documented configuration, performed slightly worse, though within variance.</p><p>But the real insight isn’t the average.</p><p><strong>It’s the variance.</strong></p><h3>The Variance Is Bigger Than the Strategy</h3><p>Standard deviation within modes: 1.3–2.0.</p><p>In Mode B, the same task scored:</p><ul><li>21/21 in one run</li><li>14/21 in another</li></ul><p>Same context. Same task. Same project.</p><p>The 14/21 run had a production bug: calling auth()-&gt;id() inside a queued listener.</p><p>No documentation prevented it.</p><p><strong>This matters more than the averages.</strong></p><blockquote><em>The difference between a good run and a bad run is larger than the difference between context strategies.</em></blockquote><p>AI coding agents are probabilistic systems.</p><p>Documentation doesn’t remove variance.</p><p>Process does.</p><h3>Why Big Context Files Don’t Move the Needle</h3><p>Because the model already reads something better:</p><p><strong>Your codebase.</strong></p><p>In every configuration, the agent:</p><ul><li>Inspected existing controllers</li><li>Copied Command/Handler structure</li><li>Mirrored repository usage</li><li>Reused test patterns</li><li>Followed module boundaries</li></ul><p>It didn’t need the architectural explanation.</p><p>It inferred the architecture from the source.</p><p>The code is the ground truth. Documentation is interpretation.</p><h3>What Context Files Are Actually Good For</h3><p>After 36 runs, only three categories consistently made sense.</p><h3>1. Organizational Constraints</h3><ul><li>PHPUnit only (no Pest)</li><li>No new dependencies without approval</li><li>No migration edits</li></ul><p>These cannot be inferred from code.</p><h3>2. Infrastructure Commands</h3><ul><li>How to run tests in Docker</li><li>Linter commands</li><li>Project-specific CLI usage</li></ul><p>These live outside the codebase.</p><h3>3. Non-Obvious Traps</h3><ul><li>Custom ID formats</li><li>Hidden infra constraints</li><li>Edge-case conventions</li></ul><p>If something looks standard but isn’t, document it.</p><p>Everything else costs tokens without improving output.</p><h3>What Changed for Me</h3><p>I thought I was engineering the AI.</p><p>In reality, I was compensating for uncertainty.</p><p>The large CLAUDE.md felt like rigor.</p><p>But the real leverage wasn’t documentation.</p><p>It was architecture.</p><p>If your codebase is:</p><ul><li>Cohesive</li><li>Consistent</li><li>Pattern-driven</li><li>Well-tested</li></ul><p>The AI performs well without explanation.</p><p>If it isn’t, no context file will save you.</p><h3>The Practical Playbook</h3><p>Keep your context file under 100 words.</p><p>Example:</p><pre># Project Rules<br>- PHPUnit only (no Pest)<br>- No new dependencies without approval<br>- Run tests: docker compose exec php-nginx php artisan test<br>- Run linter: composer fix</pre><p>That’s enough.</p><p>Invest in your system instead.</p><p>Because your architecture is the only context file the model reads every time.</p><h3>Try It Yourself</h3><ol><li>Pick a task.</li><li>Run it 3 times with your current context files.</li><li>Run it 3 times without.</li><li>Compare variance, not just the best run.</li></ol><p>You may discover what I did:</p><p>Your 2,000-word context file costs a third more in tokens. And buys you almost nothing.</p><p><em>Benchmark: 36 runs (3 modes x 4 tasks x 3 runs), February 2026. Production Laravel application, Claude CLI (claude-opus-4–6). Quality scored on a 7-criteria grid (CQRS, Repository, JSON:API, modularity, tests, conventions, code quality, max 21). Extends the findings of Gloaguen et al., </em><a href="https://arxiv.org/abs/2602.11988v1"><em>“Evaluating AGENTS.md” (arXiv:2602.11988v1, 2026)</em></a><em>. Run-to-run variance is high (std 1.3–2.0). Treat numbers as directional, not absolute.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9185b54bd4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Quality: The Quiet Shift in the Senior Developer Role]]></title>
            <link>https://medium.com/@PixelKK/the-economics-of-doing-things-right-3b8fe68c43b0?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b8fe68c43b0</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[senior-developer]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 16:41:26 GMT</pubDate>
            <atom:updated>2025-12-19T06:46:59.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TpO-xBWRf4zTWfqgQ7NiA.png" /></figure><h3><strong>Most discussions about LLMs in software development focus on speed. How fast they write code. How much productivity they bring. Who they might replace.</strong></h3><p>But if you’ve been in this industry long enough, you know speed isn’t usually the bottleneck. Maintenance is.</p><p>That’s why the speed argument doesn’t interest me. What matters is something quieter, but far more impactful. LLMs make it finally worth doing the things we always knew were important, but kept postponing because they never survived the deadline.</p><p>Documentation. Tests. Clear code reviews. Explicit technical decisions.</p><p>LLMs don’t magically make teams better. They change the <strong>economics of doing things right</strong>. And once that balance shifts, priorities follow.</p><h3>The things we always postponed</h3><p>Documentation is the perfect example. Most teams don’t lack understanding; they lack <em>written</em> understanding. The knowledge exists in people’s heads, in Slack threads, in half-remembered discussions. Turning that into something clear, structured, and readable has always been expensive.</p><p>You had to stop, switch context, find the right words, and worry about keeping it up to date.</p><p>Under pressure, that cost was hard to justify. Not because documentation wasn’t important, but because it was costly.</p><p>LLMs don’t suddenly make documentation smart. They make it <em>possible</em>. Turning a mental model into a README, explaining why a module exists, or clarifying a business rule no longer feels like burning half a day. The hard part is still knowing what to say, but expressing it is no longer the bottleneck.</p><h3>When friction disappears, intent matters more</h3><p>The same dynamic applies to tests. Writing meaningful tests was never about technical difficulty. It was about volume. Setup, boilerplate, repetitive cases, endless variations of the same patterns.</p><p>That’s exactly the kind of work LLMs excel at. They generate structure. They handle repetition. They remove friction.</p><p>What remains is the part that actually requires experience: deciding what is worth testing, what isn’t, and where the real risks lie. The thinking stays. The overhead disappears.</p><h3>Code reviews become conversations again</h3><p>One of the clearest shifts I see is in code reviews. Clear pull request descriptions, summaries of changes, and explanations of intent have always been valuable, but rarely consistent. Writing them took time, and when deadlines were tight, they were often reduced to a few rushed lines.</p><p>LLMs make it cheap to articulate intent. To explain not just <em>what</em> changed, but <em>why</em> it changed.</p><p>Consider the difference:</p><blockquote><strong>Before:</strong> A PR description might simply say <em>“Fixed bug in user auth.”</em></blockquote><blockquote><strong>Now:</strong> It takes seconds to generate: <em>“Fixed a race condition in user auth by switching to a transactional lock. I considered using an optimistic lock, but chose this approach because data consistency is critical here.”</em></blockquote><p>The code is the same. But the context, and the value for the reviewer, is completely different.</p><p>Reviews stop being about scanning diffs and start being about discussing decisions. The code becomes easier to reason about, not just today, but months later by people who weren’t even part of the original work.</p><p><em>Clarity scales. Silence doesn’t.</em></p><h3>What this really gives back to developers</h3><p>All of this doesn’t primarily make developers faster. It gives them something much more valuable: <strong>space</strong>.</p><p>When execution becomes cheaper, thinking becomes more affordable. As a developer, and even more as a senior developer, that space matters. It allows you to step back from constant delivery pressure and invest time in understanding the system, questioning assumptions, and making trade-offs explicit.</p><p>You spend more time asking <em>why</em> something exists, whether it’s the right abstraction, and what problem is actually being solved. And less time fighting the cost of expressing things clearly.</p><h3>Why this shift matters most for senior developers</h3><p>LLMs don’t make decisions. They don’t own the consequences of those decisions. They don’t deal with production incidents or long-term maintenance.</p><p>Senior developers do.</p><p>For a junior developer, an LLM might just be a way to get to a solution faster. But for a senior developer, it’s a way to ensure the solution is actually maintainable.</p><p>By lowering the cost of all the things that were previously “too long” or “too annoying,” LLMs push senior developers back toward their real value: judgment, coherence, and responsibility.</p><p>They don’t reduce the need for experience. They amplify it. Used without guidance, LLMs accelerate complexity and technical debt. Used with experienced developers, they help teams finally apply the practices they always talked about but rarely had the time to execute properly.</p><h3>Not less code, better leverage</h3><p>I don’t see this shift as writing less code. I see it as writing code in a context that is clearer, better documented, better tested, and easier to reason about.</p><p>LLMs don’t replace senior developers. They remove the excuses that prevented them from fully playing their role.</p><p>And that’s where their real impact lies.</p><p><em>A final note: This article was written with the help of an LLM. Not because I lacked ideas, but because it helped me clarify them faster. Writing clearly takes time, and not everyone is equally comfortable with words, even when they have strong, well-formed opinions worth sharing. LLMs don’t replace thinking. They help express it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b8fe68c43b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DDD in practice : building timesheet feature; from User Story to Domain Model]]></title>
            <link>https://medium.com/@PixelKK/ddd-in-practice-building-timesheet-feature-from-user-story-to-domain-model-b579cf7ecd8a?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/b579cf7ecd8a</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[devjourney]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 10:59:12 GMT</pubDate>
            <atom:updated>2025-08-07T06:57:21.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>DDD in practice : building timesheet feature; from User Story to Domain Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTCXVw8mpyz5XpYEVHPkeA.jpeg" /></figure><blockquote>If you’re new to Domain-Driven Design, I recommend reading my previous article first: <a href="https://medium.com/@PixelKK/ddd-for-backend-developers-why-is-it-so-hard-to-get-started-afc6a66741b3">DDD for Backend Developers: Why is it so hard to get started?</a>. It lays the groundwork and mindset behind the code you’re about to see.</blockquote><p>Lisa, the product owner, gathered the backend team. Malik, the developer responsible for the Timesheet domain, and Jeanne, the developer in charge of the User domain, joined her at the table.</p><p>It all started during a grooming session.</p><p>Lisa, the product owner, gathered the backend team. Malik, the developer responsible for the Timesheet domain, and Jeanne, the developer in charge of the User domain, joined her at the table.</p><blockquote><strong><em>Lisa</em></strong><em>: “The client needs to track how much time collaborators are spending each week. Eventually, we’ll use that to handle billing.”</em></blockquote><blockquote><strong><em>Malik</em></strong><em>: “Users will manually enter their working time, week by week?”</em></blockquote><blockquote><strong><em>Lisa</em></strong><em>: “Exactly. A user will input a duration for a given week. No detailed breakdown yet, just a total.”</em></blockquote><blockquote><strong><em>Jeanne</em></strong><em>: “I already developed the User domain. You’ll get the user ID, and we’ll ensure it exists before allowing any time tracking.”</em></blockquote><blockquote><strong><em>Malik</em></strong><em>: “Okey cool ! So a timesheet is a week, with a breakdown of daily durations. One per user?”</em></blockquote><blockquote><strong><em>Lisa</em></strong><em>: “Yes. And only one per week per user.”</em></blockquote><blockquote><strong><em>Malik</em></strong><em>: “Do we need to track anything other than hours? Like tasks, projects, or categories?”</em></blockquote><blockquote><strong><em>Lisa</em></strong><em>: “Not for now — just raw time.”</em></blockquote><blockquote><strong><em>Malik</em></strong><em>: “And how strict are we about the days? Do they all have to be filled? Can someone log time only for Monday and Friday?”</em></blockquote><blockquote><strong><em>Lisa</em></strong><em>: “They can fill only some days, that’s fine.”</em></blockquote><blockquote><strong><em>Jeanne</em></strong><em>: “Alright. And what about editing? Can they change a timesheet later?”</em></blockquote><blockquote><strong><em>Lisa</em></strong><em>: “Yes, but only until it’s been submitted for approval. Then it’s locked.”</em></blockquote><blockquote><strong><em>Malik</em></strong><em>: “Cool. Lisa, could you write a few BDD-style acceptance criteria in the ticket? That’ll help us clarify the logic.”</em></blockquote><blockquote><strong><em>Lisa</em></strong><em>: “Sure. I’ll do that this afternoon.”</em></blockquote><p>Lisa later updated the ticket with:</p><pre>Scenario: Create a timesheet<br>  Given a user exists<br>  When the user submits a duration for a week<br>  Then the timesheet is saved and linked to the user<br><br>Scenario: A user submits two timesheets for the same week<br>  Given a user already submitted a timesheet for the current week<br>  When they try to submit another<br>  Then an error is returned<br><br>Scenario: Submit a timesheet for validation<br>  Given a user has a draft timesheet for a given week<br>  When they submit it for validation<br>  Then the timesheet status becomes &quot;submitted&quot;<br><br>Scenario: Submit an already validated timesheet<br>  Given a timesheet has already been submitted<br>  When the user tries to submit it again<br>  Then an error is returned<br><br>Scenario: Submit a non-existent timesheet<br>  Given the user has not created a timesheet for the week<br>  When they try to submit it for validation<br>  Then an error is returned</pre><p>This small story already shows the benefit of shared language. Everyone now talks about <em>timesheets</em>, <em>weekly durations</em>, <em>submission</em>, and <em>locking : </em>terms straight from the domain.</p><p>The next morning, Malik opens his editor. But instead of reaching for a controller or a database migration, he wants to design the solution with <strong>Domain-Driven Design principles</strong>.</p><h3>Turning a User Story into a Domain: Step-by-step with DDD</h3><p>Now that the requirements are clear, we can start designing our solution using <strong>DDD principles</strong>. In this section, we’ll move from business language to code, structuring our project in three key layers:</p><ul><li>Domain/ — the heart of the business rules</li><li>Application/ — coordinates user actions (use cases)</li><li>Infrastructure/ — handles persistence, APIs, and external services</li></ul><p>Let’s go step by step.</p><h4>Define the Bounded Context</h4><p>In DDD, a <strong>Bounded Context</strong> defines the scope of a specific domain — a self-contained zone where concepts have precise meaning.</p><p>Here, the story is clearly about <strong>time tracking</strong>. So we’ll create a bounded context named:</p><pre>src/<br>└── TimeTracking/</pre><p>This context will deal with timesheets, time allocation per day, and the rules around submissions.</p><p>Jeanne talked about an existing context called User (that surely handle user interaction like authentication etc …) and other context could exist in the future: Billing/, etc. But <strong>each context is isolated</strong> and their internal models don’t leak into each other.</p><h4>Ubiquitous Language : name things like the business</h4><p>Malik doesn’t create a WorkLogEntity or WeeklyInputData.</p><p>He calls it what the business calls it: a <strong>Timesheet</strong>.</p><p>Inside TimeTracking/Domain, we add:</p><pre>// src/TimeTracking/Domain/Timesheet.php<br>namespace TimeTracking\Domain;<br><br>use Shared\ValueObjects\Week;<br>use Shared\ValueObjects\Duration;<br><br>class Timesheet<br>{<br>    /**<br>     * @param array&lt;string, Duration&gt; $dailyDurations<br>     */<br>    public function __construct(<br>        public readonly string $id,<br>        public readonly string $userId,<br>        public readonly Week $week,<br>        public readonly array $dailyDurations,<br>    ) {}<br><br>    public function totalDuration(): int<br>    {<br>        return array_reduce($this-&gt;dailyDurations, fn ($carry, Duration $d) =&gt; $carry + $d-&gt;minutes, 0);<br>    }<br>}</pre><p>We express the domain in terms <strong>the product owner would recognize</strong>: week, user, durations per day.</p><p>We’ll store Timesheet later, but the domain doesn’t care where or how yet.</p><h4>Add Status Enum</h4><p>In our conversations with Lisa, we learned that a timesheet starts as a draft, and can later be submitted for approval. Once submitted, it becomes locked.</p><p>That means our Timesheet entity has <strong>state</strong> — and we want to make those states explicit and safe.</p><p>Instead of using plain strings like “draft” or “submitted”, we’ll define an Enum. This gives us type safety and helps prevent typos or invalid values from leaking into the domain.</p><pre>// src/TimeTracking/Domain/Enum/TimesheetStatus.php<br>namespace TimeTracking\Domain\Enum;<br><br>enum TimesheetStatus: string<br>{<br>    case DRAFT = &#39;draft&#39;;<br>    case SUBMITTED = &#39;submitted&#39;;<br>}</pre><p>And we update our Timesheet entity to use it:</p><pre>public function submit(): void<br>    {<br>        if ($this-&gt;status === TimesheetStatus::SUBMITTED) {<br>            throw new \DomainException(&#39;Timesheet already submitted.&#39;);<br>        }<br><br>        $this-&gt;status = TimesheetStatus::SUBMITTED;<br>    }</pre><p>This way, the status becomes plainly part of the domain, and it becomes easier to express and enforce transitions.</p><h4>Add Value Objects for consistency</h4><p>Rather than using raw strings and floats everywhere, DDD encourages the use of <strong>Value Objects</strong> to encapsulate meaning and constraints.</p><p>Let’s create:</p><pre>// src/Shared/ValueObjects/Week.php<br>namespace Shared\ValueObjects;<br><br>class Week<br>{<br>    public function __construct(<br>        public readonly int $weekNumber,<br>        public readonly int $year,<br>    ) {<br>        if ($weekNumber &lt; 1 || $weekNumber &gt; 53) {<br>            throw new \InvalidArgumentException(&#39;Invalid week number.&#39;);<br>        }<br>    }<br><br>    public function id(): string<br>    {<br>        return sprintf(&#39;%d-W%02d&#39;, $this-&gt;year, $this-&gt;weekNumber);<br>    }<br>}</pre><p>And for durations:</p><pre>// src/Shared/ValueObjects/Duration.php<br>namespace Shared\ValueObjects;<br><br>class Duration<br>{<br>    public function __construct(public readonly int $minutes)<br>    {<br>        if ($minutes &lt; 0) {<br>            throw new \InvalidArgumentException(&#39;Duration must be &gt;= 0&#39;);<br>        }<br>    }<br>}</pre><h4>Define the Repository Contract</h4><p>We need to <strong>store and fetch</strong> Timesheets <strong>but</strong> the domain doesn’t care how.</p><p>We create an interface:</p><pre>// src/TimeTracking/Domain/Repository/TimesheetRepository.php<br>namespace TimeTracking\Domain\Repository;<br><br>use TimeTracking\Domain\Timesheet;<br><br>interface TimesheetRepository<br>{<br>    public function save(Timesheet $timesheet): void;<br><br>    public function findByUserAndWeek(string $userId, string $weekId): ?Timesheet;<br>}</pre><p>This lets the domain stay <strong>persistence-agnostic</strong>. Later, we’ll implement this interface. <a href="https://medium.com/@PixelKK/php-understanding-ports-adapters-d79beedc7d28">(if you need more informations about port &amp; adapters, check my article)</a></p><h4>Application Layer — Use Case as a Service</h4><p>Now, the <strong>Application</strong> layer coordinates behavior. This is where we write our use case: <em>“Submit a timesheet”</em>.</p><pre>// src/TimeTracking/Application/SubmitTimesheet.php<br>namespace TimeTracking\Application;<br><br>use TimeTracking\Domain\Timesheet;<br>use TimeTracking\Domain\Repository\TimesheetRepository;<br>use Shared\ValueObjects\Week;<br>use Shared\ValueObjects\Duration;<br><br>class SubmitTimesheet<br>{<br>    public function __construct(<br>        private TimesheetRepository $repository,<br>    ) {}<br><br>    public function handle(string $userId, Week $week, array $dailyDurations): void<br>    {<br>        $existing = $this-&gt;repository-&gt;findByUserAndWeek($userId, $week-&gt;toString());<br>        if ($existing !== null) {<br>            throw new \DomainException(&#39;Timesheet already submitted for this week.&#39;);<br>        }<br><br>        $durations = array_map(fn ($hours) =&gt; new Duration($hours), $dailyDurations);<br><br>        $timesheet = new Timesheet(<br>            id: uniqid(),<br>            userId: $userId,<br>            week: $week-&gt;mondayDate,<br>            dailyDurations: $durations,<br>        );<br><br>        $this-&gt;repository-&gt;save($timesheet);<br>    }<br>}</pre><p>And Submit a Timesheet for approval:</p><pre>// src/TimeTracking/Application/SubmitExistingTimesheet.php<br>namespace TimeTracking\Application;<br><br>use TimeTracking\Domain\Repository\TimesheetRepository;<br>use TimeTracking\Domain\TimesheetStatus;<br><br>class SubmitForApproval<br>{<br>    public function __construct(private TimesheetRepository $repository) {}<br><br>    public function handle(string $userId, string $weekId): void<br>    {<br>        $timesheet = $this-&gt;repository-&gt;findByUserAndWeek($userId, $weekId);<br><br>        if (!$timesheet) {<br>            throw new \DomainException(&#39;Timesheet not found.&#39;);<br>        }<br><br>        $timesheet-&gt;submit();<br>        $this-&gt;repository-&gt;save($timesheet);<br>    }<br>}</pre><p>Notice how we:</p><ul><li>Respect the domain contract (TimesheetRepository)</li><li>Validate business rules (one timesheet per user per week)</li><li>Don’t touch storage or HTTP. Just pure logic.</li></ul><h4>Infrastructure: storing timesheets</h4><p>Now that we have a domain and a use case, we need to store our timesheets somewhere. That’s the role of the Infrastructure layer: it implements our interfaces with concrete technical solutions.</p><p>We’ll start simple with an in-memory implementation to focus on logic and tests. Later, we can plug in a database repository.</p><pre>// src/TimeTracking/Infrastructure/Persistence/InMemoryTimesheetRepository.php<br>namespace TimeTracking\Infrastructure\Persistence;<br><br>use TimeTracking\Domain\Repository\TimesheetRepository;<br>use TimeTracking\Domain\Timesheet;<br><br>class InMemoryTimesheetRepository implements TimesheetRepository<br>{<br>    private array $storage = [];<br><br>    public function save(Timesheet $timesheet): void<br>    {<br>        $key = $timesheet-&gt;userId . &#39;-&#39; . $timesheet-&gt;week-&gt;id();<br>        $this-&gt;storage[$key] = $timesheet;<br>    }<br><br>    public function findByUserAndWeek(string $userId, string $weekId): ?Timesheet<br>    {<br>        $key = $userId . &#39;-&#39; . $weekId;<br>        return $this-&gt;storage[$key] ?? null;<br>    }<br>}</pre><p>This lets us test the behavior easily, without setting up a database yet.</p><h4>Http implementation</h4><p>For routing, we’ll use <a href="https://github.com/bramus/router">bramus/router</a> — a minimalistic router that works perfectly in small PSR-4 setups.</p><p>We’ll place the HTTP layer in Application/Http/, since it’s about receiving external commands (user input) and calling the Application layer accordingly.</p><p>For routes :</p><pre>// routes/web.php<br>use Bramus\Router\Router;<br>use TimeTracking\Application\Http\TimesheetController;<br><br>$router = new Router();<br><br>$router-&gt;post(&#39;/timesheets&#39;, [TimesheetController::class, &#39;submit&#39;]);<br>$router-&gt;post(&#39;/timesheets/(\d{1,2})/(\d{4})/submit&#39;, function ($week, $year) {<br>    TimesheetController::submitForApproval($week, $year);<br>});<br><br>$router-&gt;run();</pre><p>And controllers :</p><pre>// src/TimeTracking/Application/Http/TimesheetController.php<br>namespace TimeTracking\Application\Http;<br><br>use TimeTracking\Application\SubmitTimesheet;<br>use TimeTracking\Application\ListTimesheets;<br>use TimeTracking\Infrastructure\Persistence\InMemoryTimesheetRepository;<br>use Shared\ValueObjects\Week;<br><br>class TimesheetController<br>{<br>    public static function submit(): void<br>    {<br>        $data = json_decode(file_get_contents(&#39;php://input&#39;), true);<br><br>        $repository = new InMemoryTimesheetRepository();<br>        $useCase = new SubmitTimesheet($repository);<br><br>        try {<br>            $useCase-&gt;handle(<br>                userId: $data[&#39;user_id&#39;],<br>                week: new Week($data[&#39;week&#39;], $data[&#39;year&#39;]),<br>                dailyDurations: $data[&#39;daily_durations&#39;],<br>            );<br>            http_response_code(201);<br>        } catch (\DomainException $e) {<br>            http_response_code(400);<br>            echo json_encode([&#39;error&#39; =&gt; $e-&gt;getMessage()]);<br>        }<br>    }<br><br>    public static function submitForApproval(string $week, string $year): void<br>    {<br>        $userId = $_GET[&#39;user_id&#39;] ?? null;<br>    <br>        if (!$userId) {<br>            http_response_code(400);<br>            echo json_encode([&#39;error&#39; =&gt; &#39;Missing user_id&#39;]);<br>            return;<br>        }<br>    <br>        $repository = new InMemoryTimesheetRepository();<br>        $useCase = new SubmitForApproval($repository);<br>    <br>        try {<br>            $weekObj = new Week((int) $week, (int) $year);<br>            $useCase-&gt;handle($userId, $weekObj-&gt;id());<br>            http_response_code(200);<br>        } catch (\DomainException $e) {<br>            http_response_code(400);<br>            echo json_encode([&#39;error&#39; =&gt; $e-&gt;getMessage()]);<br>        }<br>    }<br>}</pre><p><em>Note: in a real app, repositories would be dependency-injected and shared, but for this simplified project, we instantiate them per request.</em></p><h4>PHPUnit: Writing tests BDD-style</h4><p>We write tests using a naming convention that reflects the Given/When/Then structure</p><pre>use PHPUnit\Framework\TestCase;<br>use TimeTracking\Application\SubmitTimesheet;<br>use TimeTracking\Infrastructure\Persistence\InMemoryTimesheetRepository;<br>use Shared\ValueObjects\Week;<br><br>class SubmitTimesheetTest extends TestCase<br>{<br>    public function test_submit_timesheet_when_none_exists_given_valid_data_then_it_is_saved(): void<br>    {<br>        $repo = new InMemoryTimesheetRepository();<br>        $useCase = new SubmitTimesheet($repo);<br><br>        $week = new Week(27, 2024);<br><br>        $useCase-&gt;handle(<br>            userId: &#39;user-123&#39;,<br>            week: $week,<br>            dailyDurations: [<br>                &#39;monday&#39; =&gt; 120,<br>                &#39;tuesday&#39; =&gt; 240,<br>            ]<br>        );<br><br>        $this-&gt;assertNotNull($repo-&gt;findByUserAndWeek(&#39;user-123&#39;, $week-&gt;id()));<br>    }<br><br>    public function test_submit_timesheet_when_already_exists_given_same_user_and_week_then_it_throws(): void<br>    {<br>        $this-&gt;expectException(\DomainException::class);<br><br>        $repo = new InMemoryTimesheetRepository();<br>        $useCase = new SubmitTimesheet($repo);<br>        $week = new Week(27, 2024);<br><br>        $useCase-&gt;handle(&#39;user-123&#39;, $week, [&#39;monday&#39; =&gt; 60]);<br>        $useCase-&gt;handle(&#39;user-123&#39;, $week, [&#39;tuesday&#39; =&gt; 60]); // should fail<br>    }<br>}</pre><pre>use PHPUnit\Framework\TestCase;<br>use TimeTracking\Application\SubmitExistingTimesheet;<br>use TimeTracking\Application\SubmitTimesheet;<br>use TimeTracking\Infrastructure\Persistence\InMemoryTimesheetRepository;<br>use Shared\ValueObjects\Week;<br><br>class SubmitForApprovalTimesheetTest extends TestCase<br>{<br>    public function test_submit_for_approval_timesheet_when_it_is_draft_given_valid_user_and_week_then_it_is_submitted(): void<br>    {<br>        $repo = new InMemoryTimesheetRepository();<br>        $week = new Week(27, 2024);<br><br>        $creator = new SubmitTimesheet($repo);<br>        $creator-&gt;handle(&#39;user-123&#39;, $week, [&#39;monday&#39; =&gt; 60]);<br><br>        $submitter = new SubmitForApprovalTimesheet($repo);<br>        $submitter-&gt;handle(&#39;user-123&#39;, $week-&gt;id());<br><br>        $timesheet = $repo-&gt;findByUserAndWeek(&#39;user-123&#39;, $week-&gt;id());<br><br>        $this-&gt;assertEquals(&#39;submitted&#39;, $timesheet-&gt;status-&gt;value);<br>    }<br><br>    public function test_submit_for_approval_timesheet_when_already_submitted_then_it_throws(): void<br>    {<br>        $this-&gt;expectException(\DomainException::class);<br><br>        $repo = new InMemoryTimesheetRepository();<br>        $week = new Week(27, 2024);<br><br>        $creator = new SubmitForApprovalTimesheet($repo);<br>        $creator-&gt;handle(&#39;user-123&#39;, $week, [&#39;monday&#39; =&gt; 60]);<br><br>        $submitter = new SubmitExistingTimesheet($repo);<br>        $submitter-&gt;handle(&#39;user-123&#39;, $week-&gt;id());<br>        $submitter-&gt;handle(&#39;user-123&#39;, $week-&gt;id()); // second call should throw<br>    }<br>}</pre><h4>Wrapping Up</h4><p>What started as a casual grooming session turned into a fully isolated, testable, and expressive domain module, driven by Domain-Driven Design.</p><p>By working from the business language and scenarios, we built:</p><ul><li>A clear <strong>bounded context</strong> (TimeTracking)</li><li>A rich <strong>domain model</strong> with value objects and enum-based state</li><li>An <strong>application layer</strong> that coordinates the use cases</li><li>A pluggable <strong>infrastructure</strong>, starting with in-memory storage</li><li>A thin <strong>HTTP interface</strong>, decoupled from the domain</li><li><strong>BDD-style tests</strong> that reflect the real business behavior</li></ul><p>And perhaps most importantly:</p><p>We never wrote a single SQL query or controller before understanding <em>what the business actually needed</em>.</p><p>This example is intentionally simple, but shows how DDD helps you structure even the most basic features in a way that’s robust, extensible, and deeply aligned with your users’ mental model.</p><h3>You now have the foundations of DDD, but there’s so much more to explore</h3><p>DDD doesn’t stop here. As your system grows in complexity, you’ll face new challenges, and DDD offers powerful tools to help you scale without losing control. Here’s a quick tour of the most common ones:</p><h4>Aggregates: grouping things that change together</h4><p>Sometimes, multiple objects are tightly linked and must be updated together (think of an Order and its LineItems). Aggregates define a <strong>consistency boundary</strong> around related entities and ensure <strong>invariants</strong> are maintained.</p><h4>Domain Events: saying “something just happened”</h4><p>Your domain can express meaningful moments: “Timesheet was submitted”, “User was deactivated”… Domain Events allow <strong>decoupled reactions</strong> to those events, like triggering an email, a billing process, or an audit log, without bloating your core logic.</p><h4>Event Sourcing: tracking the full history</h4><p>Instead of storing only the final state, you store <strong>every event that changed it</strong>. You can replay them to reconstruct the current state or any past state. Great for use cases where <strong>history matters</strong>, like finance, audits, or workflows.</p><h4>CQRS: separating reading from writing</h4><p>When your application grows, reading and writing data often have <strong>very different needs</strong>. CQRS (Command Query Responsibility Segregation) splits those concerns, so you can optimize reads (e.g., via projections or Elasticsearch) without impacting writes. <a href="https://medium.com/@PixelKK/cqrs-with-laravel-what-it-is-when-to-use-it-and-how-i-implemented-it-d83ec387d926"><em>Have a look on my previous article on CQRS</em></a></p><h4>Context Mapping: making boundaries explicit</h4><p>When multiple teams work on different domains (e.g., Users, Billing, TimeTracking), you need to define <strong>how they interact</strong>. DDD offers patterns to clarify those boundaries:</p><ul><li><strong>Conformist</strong>: your context adapts to another’s model,</li><li><strong>Anti-Corruption Layer</strong>: you transform their model to protect your own,</li><li><strong>Shared Kernel</strong>: you share a stable subset if necessary.</li></ul><p>And so many more …</p><p>Don’t forget to check out my <a href="https://medium.com/@PixelKK/ddd-for-backend-developers-why-is-it-so-hard-to-get-started-afc6a66741b3">previous article on why DDD is hard to start</a> if you haven’t read it yet, it lays the conceptual groundwork for everything we’ve implemented here.</p><p>Github link : <a href="https://github.com/mouize/demo-ddd-light">https://github.com/mouize/demo-ddd-light</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b579cf7ecd8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DDD for backend developers: why is it so hard to get started]]></title>
            <link>https://medium.com/@PixelKK/ddd-for-backend-developers-why-is-it-so-hard-to-get-started-afc6a66741b3?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/afc6a66741b3</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 14:23:27 GMT</pubDate>
            <atom:updated>2025-08-07T06:12:02.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="DDD for backend developers: why is it so hard to get started" src="https://cdn-images-1.medium.com/max/1024/1*ndX_al3WPMM8ACtHelB4gw.jpeg" /></figure><p><strong>Domain-Driven Design (DDD)</strong> is often praised by senior engineers, architects, and books full of hexagons, but for backend developers just trying to write clean, testable code, it can feel overcomplicated and abstract. If that’s you … you’re not alone!</p><p>In this article, I’ll break down why DDD feels intimidating at first, how it differs from what we usually do in PHP, and how to gradually adopt it without rewriting everything or becoming an architecture astronaut.</p><h3>Why does DDD feel complicated at first?</h3><h4>We’re trained for data-first thinking</h4><p>In Laravel/Symfony for instance, you might start by writing a migration, then a model/entity, then a controller method to return data.</p><p><strong>The data drives the code </strong>and that’s what we call <strong>data-driven design</strong>.</p><p>In DDD, it’s the opposite: the <strong>domain</strong> drives everything. You design the code around the <strong>business rules and language, </strong>and persistence becomes an implementation detail.</p><p>That flip is huge and it’s not how frameworks teach us.</p><h4>Frameworks give us comfort, but not boundaries.</h4><p>Laravel, Symfony and others give us amazing tools: routing, validation, ORM, service containers…</p><p>But this also means we get lazy with design. We dump logic in controllers or “services”, and before we know it we’ve built a procedural app with modern tooling.</p><p><strong>DDD introduces boundaries:</strong></p><ul><li>Domain vs Infrastructure</li><li>Core logic vs glue code</li><li>Clear contracts for external stuff</li></ul><p>Those boundaries make code easier to reason about. But when you’re used to “just writing features,” it’s easy to feel overwhelmed.</p><h4>So what is DDD, really?</h4><p>Forget the big words for a second. <strong>DDD is just a way to organize your code around the business, not the tools.</strong></p><p>That means:</p><ul><li>Your core logic lives in a clean <strong>Domain layer</strong></li><li>Anything external (DB, APIs, files) goes in <strong>Infrastructure</strong></li><li>You define <strong>Application</strong> logic to coordinate behaviors</li><li>You write <strong>contracts (interfaces)</strong> instead of coupling to tools</li></ul><p>This allows you to test, refactor, and extend more easily. <strong>It’s not magic, it’s just boundaries.</strong></p><h4>Some key concepts that help make sense of it</h4><p>Here are the core concepts that helped me stop struggling with DDD:</p><p><strong>Ubiquitous Language </strong>helps to use the same language everywhere: in your code, with the product team, and with the business. If your client talks about a “timesheet,” don’t call it WorkLogEntry. Call it Timesheet. Clarity beats cleverness.</p><p><strong>Bounded Contexts</strong> keep each domain small and focused. A “timesheet” in HR may not mean the same as a “timesheet” in finance. Define boundaries.</p><p>An <strong>Entity</strong> has an identity (e.g., a User), while a <strong>ValueObject</strong> represents a concept with no identity (e.g., Email, Duration, DateRange)</p><p><strong>Repositories </strong>abstract how you fetch/save domain objects — whether it’s MySQL, an API, or Redis.</p><h4>Why the learning curve feels steep</h4><p>Because most backend devs are used to <strong>driving the design from the tech side</strong> and not from the business.</p><p>DDD forces you to stop thinking in terms of tables and controllers and start thinking in terms of behaviors and intent. That takes practice. Especially when:</p><ul><li>You work on solo/small teams without clear domain experts.</li><li>You’ve always mixed persistence logic with business logic.</li><li>You’re constrained by a framework that encourages fat models and active records.</li></ul><p>But once you flip the switch, things start to feel cleaner. Tests become easier. Changes are more localized. Business rules have a real home.</p><p>The good news? You don’t need to go full-on DDD to benefit. Even small steps toward separating your domain from your tech stack can bring clarity and sanity.</p><h4>Example Project Structure</h4><p>Here’s a typical project layout for a DDD-lite approach:</p><pre>src/<br>├── TimeTracking/         ← Bounded context<br>│   ├── Domain/           ← Business concepts (Entities, ValueObjects, Interfaces)<br>│   │   ├── Timesheet.php                 ← Entity<br>│   │   ├── Repository/<br>│   │   │   └── TimesheetRepository.php   ← Interface (contracts)<br>│   ├── Application/      ← orchestrates the domain to solve use cases.<br>│   │   ├── CreateTimesheet.php           ← Use case (Application Service)<br>│   ├── Infrastructure/   ← implements technical concerns<br>│   │   ├── Persistence/<br>│   │   │   └── InMemoryTimesheetRepository.php ← Storing in-memory<br>├── Shared/               ← Shared Kernel (optional)<br>│   ├── ValueObjects/<br>│   │   └── Email.php                     ← Reused in multiple contexts<br>│   └── Services/<br>│       └── Clock.php                     ← Centralized clock for time consistency</pre><p><strong>What this structure tells you</strong></p><p><strong>TimeTracking/</strong> is the <strong>business domain</strong> we’re modeling. In a bigger app, you’d have more contexts like Billing/, HR/, Recruitment/…</p><p>Inside it, you clearly see the <strong>DDD layers</strong>:</p><ul><li>Domain/: contains the business rules and vocabulary.</li><li>Application/: contains the orchestration of those rules (use cases).</li><li>Infrastructure/: contains the technical implementations (persistence, HTTP…).</li><li>Shared<strong>/</strong>: optional, contains cross-cutting concerns or shared concepts like User, Email, Clock.</li></ul><h4>Bonus: BDD bridges the gap</h4><p><strong>Behavior-Driven Development (BDD)</strong> can help with this transition. It invites product owners and devs to collaborate on <strong>rules</strong>, written in plain language (Given/When/Then). From those, you write tests and your domain grows around real, validated needs.</p><p><em>With BDD, product owners help define the rules in plain language. Developers turn them into executable tests. This closes the gap between business needs and code.</em></p><p>This makes it easier to work <strong>from the business</strong> instead of just the code.</p><h4>Real-world example (next article teaser)</h4><p>In the next article, I’ll walk you through a small real-world project built from scratch using a light DDD structure with no framework, just PHP, PSR-4, and a clean separation of domain, application, and infrastructure layers.</p><p><a href="https://medium.com/@PixelKK/ddd-in-practice-building-timesheet-feature-from-user-story-to-domain-model-b579cf7ecd8a">We’ll build something concrete like a time tracking system, and you’ll see how the DDD pieces fit together in a practical way.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afc6a66741b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[PHP] Understanding Ports & Adapters]]></title>
            <link>https://medium.com/@PixelKK/php-understanding-ports-adapters-d79beedc7d28?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79beedc7d28</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 13:57:46 GMT</pubDate>
            <atom:updated>2025-09-10T21:24:07.180Z</atom:updated>
            <content:encoded><![CDATA[<h3>Discovering Ports &amp; Adapters: The Foundation of Hexagonal Architecture</h3><p>Ports and Adapters is a well-known and widely used design pattern, often without even realizing it. Foundational to maintainable and testable applications, this pattern separates the <em>what</em> (your core logic) from the <em>how</em> (external systems or tools). It’s commonly embedded in frameworks like Symfony and Laravel through features like dependency injection, contracts, and service containers.</p><p>In this article, we’ll focus specifically on the Ports and Adapters concept, <em>without diving into full Hexagonal architecture</em>.</p><h3>What Are Ports &amp; Adapters?</h3><p><strong>Ports</strong> are interfaces that define the actions your application expects (inputs) or provides (outputs). Think of them as your contracts.</p><p><strong>Adapters</strong> are concrete implementations of those interfaces. They allow communication with external systems: databases, APIs, file storage, queues, etc.</p><p>By depending on interfaces rather than implementations, your core application becomes easier to test, change, and extend. For instance:</p><ul><li>You can mock external services in tests.</li><li>You can change how data is stored without touching business logic.</li><li>You can add new integrations just by writing a new adapter.</li></ul><p>This is how frameworks like Laravel let you swap out mail drivers, queue backends, or filesystem disks with ease.</p><h3><strong>The Use Case: Configurable Data Importer</strong></h3><p>Let’s walk through a typical example (PHP) to see Ports &amp; Adapters in action: a system that <strong>imports user data from multiple sources</strong> (CSV, HTTP API) and <strong>stores them in multiple formats</strong> (MySQL, JSONL files).</p><p>We want to:</p><ul><li>Add new sources/targets without modifying the core logic</li><li>Drive the behavior through config</li><li>Keep the application decoupled from external systems</li></ul><h3>Step 1: Define Contracts (Ports)</h3><p>Let’s define our contracts :</p><pre>interface ImportSourceInterface<br>{<br>    /** @return Collection&lt;ImportDto&gt; */<br>    public function fetch(): Collection;<br>}<br><br>interface ImportTargetInterface<br>{<br>    /** @param Collection&lt;ImportDto&gt; $records */<br>    public function store(Collection $records): void;<br>}</pre><p>The ImportDto is a simple data carrier:</p><pre>class ImportDto<br>{<br>    public function __construct(<br>        public readonly string $email,<br>        public readonly string $name,<br>    ) {}<br>}</pre><h3>Step 2: Create Adapters</h3><pre>namespace App\Adapters\Sources;<br><br>use App\Contracts\ImportSourceInterface;<br>use App\DTO\ImportDto;<br>use Illuminate\Support\Collection;<br><br>class CsvFileSource implements ImportSourceInterface<br>{<br>    public function __construct(private string $path) {}<br><br>    /**<br>     * @return Collection&lt;ImportDto&gt;<br>     */<br>    public function fetch(): Collection<br>    {<br>        $rows = collect();<br><br>        if (! file_exists($this-&gt;path)) {<br>            throw new \RuntimeException(&quot;CSV file not found at {$this-&gt;path}&quot;);<br>        }<br><br>        $handle = fopen($this-&gt;path, &#39;r&#39;);<br>        $headers = fgetcsv($handle);<br><br>        while ($line = fgetcsv($handle)) {<br>            $row = array_combine($headers, $line);<br>            $rows-&gt;push(new ImportDto(<br>                email: $row[&#39;email&#39;] ?? &#39;&#39;,<br>                name: $row[&#39;name&#39;] ?? &#39;&#39;,<br>            ));<br>        }<br><br>        fclose($handle);<br><br>        return $rows;<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Adapters\Sources;<br><br>use App\Contracts\ImportSourceInterface;<br>use App\DTO\ImportDto;<br>use Illuminate\Support\Collection;<br>use Illuminate\Support\Facades\Http;<br><br>class HttpClientSource implements ImportSourceInterface<br>{<br>    public function __construct(private string $url, private ?string $token = null) {}<br><br>    /**<br>     * @return Collection&lt;ImportDto&gt;<br>     */<br>    public function fetch(): Collection<br>    {<br>        $response = Http::withToken($this-&gt;token)-&gt;get($this-&gt;url);<br><br>        if (! $response-&gt;successful()) {<br>            throw new \RuntimeException(&#39;Unable to fetch data from HTTP source.&#39;);<br>        }<br><br>        return collect($response-&gt;json())<br>            -&gt;map(fn (array $item) =&gt; new ImportDto(<br>                email: $item[&#39;email&#39;] ?? &#39;&#39;,<br>                name: $item[&#39;name&#39;] ?? &#39;&#39;,<br>            ));<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Adapters\Targets;<br><br>use App\Contracts\ImportTargetInterface;<br>use App\DTO\ImportDto;<br>use App\Models\ImportedUser;<br>use Illuminate\Support\Collection;<br><br>class EloquentStorage implements ImportTargetInterface<br>{<br>    public function store(Collection $records): void<br>    {<br>        $users = $records-&gt;map(function (ImportDto $record) {<br>            return [<br>                &#39;email&#39; =&gt; $record-&gt;email,<br>                &#39;name&#39; =&gt; $record-&gt;name,<br>            ];<br>        });<br><br>        ImportedUser::insert($users-&gt;toArray());<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Adapters\Targets;<br><br>use App\Contracts\ImportTargetInterface;<br>use Illuminate\Support\Collection;<br><br>class FileStorage implements ImportTargetInterface<br>{<br>    public function __construct(<br>        private string $path,<br>    ) {}<br><br>    public function store(Collection $records): void<br>    {<br>        file_put_contents(<br>            filename: $this-&gt;path,<br>            data: json_encode($records)<br>        );<br>    }<br>}</pre><p>Each adapter only cares about its specific task. They don’t know where they’re called from or why. That’s the job of our orchestration layer.</p><h3>Step 3: Config-Driven Behavior:</h3><p>We use a single port-adapters.php config file to list available sources, targets, and define the jobs.</p><pre>&lt;?php<br><br>return [<br>    //List of available sources<br>    &#39;sources&#39; =&gt; [<br>        &#39;http_users&#39; =&gt; [<br>            &#39;class&#39; =&gt; \App\Adapters\Sources\HttpClientSource::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;url&#39; =&gt; env(&#39;USERS_API_URL&#39;),<br>                &#39;token&#39; =&gt; env(&#39;USERS_API_TOKEN&#39;),<br>            ],<br>        ],<br>        &#39;local_csv&#39; =&gt; [<br>            &#39;class&#39; =&gt; \App\Adapters\Sources\CsvFileSource::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;path&#39; =&gt; storage_path(&#39;imports/users.csv&#39;),<br>            ],<br>        ],<br>    ],<br><br>    //List of available targets<br>    &#39;targets&#39; =&gt; [<br>        &#39;mysql&#39; =&gt; [<br>            &#39;class&#39; =&gt; \App\Adapters\Targets\EloquentStorage::class,<br>            &#39;arguments&#39; =&gt; [],<br>        ],<br>        &#39;file&#39; =&gt; [<br>            &#39;class&#39; =&gt; \App\Adapters\Targets\FileStorage::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;path&#39; =&gt; storage_path(&#39;imports/output/users.jsonl&#39;),<br>            ],<br>        ],<br>    ],<br><br>    //Import job definitions (source ↔ target)<br>    &#39;jobs&#39; =&gt; [<br>        &#39;users_from_http&#39; =&gt; [<br>            &#39;source&#39; =&gt; &#39;http_users&#39;,<br>            &#39;target&#39; =&gt; &#39;file&#39;,<br>        ],<br>        &#39;users_from_csv&#39; =&gt; [<br>            &#39;source&#39; =&gt; &#39;local_csv&#39;,<br>            &#39;target&#39; =&gt; &#39;mysql&#39;,<br>        ],<br>    ],<br><br>];</pre><p>This allows defining import jobs like users_from_http or users_from_csv dynamically.</p><h3>Step 4: Job Runner Service</h3><pre>&lt;?php<br><br>namespace App\Services;<br><br>use App\Contracts\ImportSourceInterface;<br>use App\Contracts\ImportTargetInterface;<br><br>class ImportJobRunner<br>{<br>    public function __construct(private string $jobName) {}<br><br>    public function run(): void<br>    {<br>        $job = config(&quot;import_jobs.{$this-&gt;jobName}&quot;);<br>        $sourceConfig = config(&quot;import_sources.{$job[&#39;source&#39;]}&quot;);<br>        $targetConfig = config(&quot;import_targets.{$job[&#39;target&#39;]}&quot;);<br><br>        $source = $this-&gt;makeAdapter($sourceConfig, ImportSourceInterface::class);<br>        $target = $this-&gt;makeAdapter($targetConfig, ImportTargetInterface::class);<br><br>        $target-&gt;store(<br>            $source-&gt;fetch()<br>        );<br><br>    }<br><br>    protected function makeAdapter(array $config, string $interface): object<br>    {<br>        $instance = app()-&gt;makeWith($config[&#39;class&#39;], $config[&#39;arguments&#39;] ?? []);<br><br>        if (! $instance instanceof $interface) {<br>            throw new \RuntimeException(&#39;Adapter does not implement required interface.&#39;);<br>        }<br><br>        return $instance;<br>    }<br>}</pre><p>This is the heart of the system: given a job name, it dynamically resolves the correct adapters and runs the import.</p><h3><strong>Functional Tests</strong></h3><p>I wrote tests to cover each combination:</p><ul><li>CSV -&gt; MySQL</li><li>CSV -&gt; File</li><li>HTTP -&gt; MySQL</li><li>HTTP -&gt; File</li></ul><pre>&lt;?php<br><br>namespace Tests\Feature;<br><br>use App\Adapters\Sources\CsvFileSource;<br>use App\Adapters\Sources\HttpClientSource;<br>use App\Adapters\Targets\EloquentStorage;<br>use App\Adapters\Targets\FileStorage;<br>use App\Services\ImportJobRunner;<br>use Illuminate\Foundation\Testing\RefreshDatabase;<br>use Illuminate\Support\Facades\File;<br>use Illuminate\Support\Facades\Http;<br>use PHPUnit\Framework\Attributes\Test;<br>use Tests\TestCase;<br><br>class ImportJobRunnerTest extends TestCase<br>{<br>    use RefreshDatabase;<br><br>    #[Test]<br>    public function it_imports_from_csv_to_mysql(): void<br>    {<br>        config()-&gt;set(&#39;import_jobs.users_from_csv&#39;, [<br>            &#39;source&#39; =&gt; &#39;csv_users&#39;,<br>            &#39;target&#39; =&gt; &#39;mysql&#39;,<br>        ]);<br><br>        config()-&gt;set(&#39;import_sources.csv_users&#39;, [<br>            &#39;class&#39; =&gt; CsvFileSource::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;path&#39; =&gt; storage_path(&#39;imports/users.csv&#39;),<br>            ],<br>        ]);<br><br>        config()-&gt;set(&#39;import_targets.mysql&#39;, [<br>            &#39;class&#39; =&gt; EloquentStorage::class,<br>            &#39;arguments&#39; =&gt; [],<br>        ]);<br><br>        (new ImportJobRunner(&#39;users_from_csv&#39;))-&gt;run();<br><br>        $this-&gt;assertDatabaseCount(&#39;imported_users&#39;, 4);<br>        $this-&gt;assertDatabaseHas(&#39;imported_users&#39;, [&#39;email&#39; =&gt; &#39;alice@example.com&#39;]);<br>        $this-&gt;assertDatabaseHas(&#39;imported_users&#39;, [&#39;email&#39; =&gt; &#39;bob@example.com&#39;]);<br>        $this-&gt;assertDatabaseHas(&#39;imported_users&#39;, [&#39;email&#39; =&gt; &#39;carla@example.com&#39;]);<br>        $this-&gt;assertDatabaseHas(&#39;imported_users&#39;, [&#39;email&#39; =&gt; &#39;mohamed@example.com&#39;]);<br><br>    }<br><br>    #[Test]<br>    public function it_imports_from_csv_to_file(): void<br>    {<br>        config()-&gt;set(&#39;import_jobs.csv_to_file&#39;, [<br>            &#39;source&#39; =&gt; &#39;csv_users&#39;,<br>            &#39;target&#39; =&gt; &#39;file&#39;,<br>        ]);<br><br>        config()-&gt;set(&#39;import_sources.csv_users&#39;, [<br>            &#39;class&#39; =&gt; CsvFileSource::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;path&#39; =&gt; storage_path(&#39;imports/users.csv&#39;),<br>            ],<br>        ]);<br><br>        config()-&gt;set(&#39;import_targets.file&#39;, [<br>            &#39;class&#39; =&gt; FileStorage::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;path&#39; =&gt; storage_path(&#39;imports/users.jsonl&#39;),<br>            ],<br>        ]);<br><br>        (new ImportJobRunner(&#39;csv_to_file&#39;))-&gt;run();<br><br>        $this-&gt;assertFileExists(storage_path(&#39;imports/users.jsonl&#39;));<br>        $content = File::get(storage_path(&#39;imports/users.jsonl&#39;));<br><br>        $this-&gt;assertStringContainsString(&#39;mohamed@example.com&#39;, $content);<br>        $this-&gt;assertCount(4, json_decode($content, true));<br>    }<br><br>    #[Test]<br>    public function it_imports_from_http_to_mysql(): void<br>    {<br>        Http::fake([<br>            &#39;*&#39; =&gt; Http::response([<br>                [&#39;email&#39; =&gt; &#39;foo@example.com&#39;, &#39;name&#39; =&gt; &#39;Foo&#39;],<br>                [&#39;email&#39; =&gt; &#39;bar@example.com&#39;, &#39;name&#39; =&gt; &#39;Bar&#39;],<br>            ]),<br>        ]);<br><br>        config()-&gt;set(&#39;import_jobs.http_to_mysql&#39;, [<br>            &#39;source&#39; =&gt; &#39;http_users&#39;,<br>            &#39;target&#39; =&gt; &#39;mysql&#39;,<br>        ]);<br><br>        config()-&gt;set(&#39;import_sources.http_users&#39;, [<br>            &#39;class&#39; =&gt; HttpClientSource::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;url&#39; =&gt; &#39;https://dummy.test/api/users&#39;,<br>                &#39;token&#39; =&gt; &#39;dummy_token&#39;,<br>            ],<br>        ]);<br><br>        config()-&gt;set(&#39;import_targets.mysql&#39;, [<br>            &#39;class&#39; =&gt; EloquentStorage::class,<br>            &#39;arguments&#39; =&gt; [],<br>        ]);<br><br>        (new ImportJobRunner(&#39;http_to_mysql&#39;))-&gt;run();<br><br>        $this-&gt;assertDatabaseCount(&#39;imported_users&#39;, 2);<br>        $this-&gt;assertDatabaseHas(&#39;imported_users&#39;, [&#39;email&#39; =&gt; &#39;foo@example.com&#39;]);<br>        $this-&gt;assertDatabaseHas(&#39;imported_users&#39;, [&#39;email&#39; =&gt; &#39;bar@example.com&#39;]);<br>    }<br><br>    #[Test]<br>    public function it_imports_from_http_to_file(): void<br>    {<br>        Http::fake([<br>            &#39;*&#39; =&gt; Http::response([<br>                [&#39;email&#39; =&gt; &#39;zara@example.com&#39;, &#39;name&#39; =&gt; &#39;Zara&#39;],<br>            ]),<br>        ]);<br><br>        config()-&gt;set(&#39;import_jobs.http_to_file&#39;, [<br>            &#39;source&#39; =&gt; &#39;http_users&#39;,<br>            &#39;target&#39; =&gt; &#39;file&#39;,<br>        ]);<br><br>        config()-&gt;set(&#39;import_sources.http_users&#39;, [<br>            &#39;class&#39; =&gt; HttpClientSource::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;url&#39; =&gt; &#39;https://dummy.test/api/users&#39;,<br>                &#39;token&#39; =&gt; &#39;dummy_token&#39;,<br>            ],<br>        ]);<br><br>        config()-&gt;set(&#39;import_targets.file&#39;, [<br>            &#39;class&#39; =&gt; FileStorage::class,<br>            &#39;arguments&#39; =&gt; [<br>                &#39;path&#39; =&gt; storage_path(&#39;imports/users.jsonl&#39;),<br>            ],<br>        ]);<br><br>        (new ImportJobRunner(&#39;http_to_file&#39;))-&gt;run();<br><br>        $this-&gt;assertFileExists(storage_path(&#39;imports/users.jsonl&#39;));<br>        $this-&gt;assertStringContainsString(&#39;zara@example.com&#39;, File::get(storage_path(&#39;imports/users.jsonl&#39;)));<br>    }<br><br>    #[Test]<br>    public function it_throws_if_adapter_does_not_implement_interface(): void<br>    {<br>        config()-&gt;set(&#39;import_jobs.invalid_adapter&#39;, [<br>            &#39;source&#39; =&gt; &#39;invalid_source&#39;,<br>            &#39;target&#39; =&gt; &#39;mysql&#39;,<br>        ]);<br><br>        config()-&gt;set(&#39;import_sources.invalid_source&#39;, [<br>            &#39;class&#39; =&gt; \stdClass::class, // Ne respecte pas ImportSourceInterface<br>            &#39;arguments&#39; =&gt; [],<br>        ]);<br><br>        $this-&gt;expectException(\RuntimeException::class);<br>        $this-&gt;expectExceptionMessage(&#39;Adapter does not implement required interface&#39;);<br><br>        (new ImportJobRunner(&#39;invalid_adapter&#39;))-&gt;run();<br>    }<br>}</pre><p>These tests:</p><ul><li>Ensure the correct integration between source &amp; target</li><li>Test that the contracts are respected</li><li>Prove that the system can adapt dynamically to config changes</li></ul><h3>Conclusion</h3><p>Ports &amp; Adapters isn’t just a theory, it’s a powerful way to write maintainable code.</p><ul><li>Your business logic doesn’t know how data is fetched or stored.</li><li>Your adapters don’t know why they’re used, just how.</li><li>Your application becomes easier to test and evolve.</li></ul><blockquote>Github repository : <a href="https://github.com/mouize/demo-ports-adapter">https://github.com/mouize/demo-ports-adapter</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79beedc7d28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS with Laravel: What It Is, When to Use It, and How I Implemented It]]></title>
            <link>https://medium.com/@PixelKK/cqrs-with-laravel-what-it-is-when-to-use-it-and-how-i-implemented-it-d83ec387d926?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/d83ec387d926</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 11:16:43 GMT</pubDate>
            <atom:updated>2025-04-28T11:16:43.173Z</atom:updated>
            <content:encoded><![CDATA[<p>As business logic becomes more complex, I’ve often found myself dealing with bloated services, classes that do too much, and tests that are hard to maintain. That’s when I started applying the <strong>CQRS</strong> pattern (Command Query Responsibility Segregation) in my Laravel projects, and honestly, it’s been a game changer.</p><p>In this article, I’ll explain what <strong>CQRS</strong> is, when it makes sense to use it (and when not), how to implement it in Laravel, and walk you through a concrete use case: generating a monthly invoice.</p><h3>What is CQRS?</h3><p>CQRS is an architectural pattern that separates <strong>commands </strong>aka<strong> </strong>operations that change the system’s statefrom <strong>queries</strong>, which only read data.</p><p>Why bother separating them?</p><ul><li>It reflects <strong>business intent</strong> more clearly in code</li><li>It makes <strong>unit testing</strong> much easier</li><li>It keeps classes <strong>small and focused</strong></li><li>In some cases, it improves <strong>performance</strong> by optimizing read and write paths separately</li></ul><p>This is more than just using different methods: we create separate classes for each action, typically organized under Commands/ and Queries/, each with its own handler.</p><h3>Setting up CQRS in Laravel</h3><p>To keep things clean and easy to find, I usually organize commands and queries under a CQRS folder. Here&#39;s a typical folder structure:</p><pre>app/<br>├── CQRS/<br>│   ├── Commands/<br>│   │   ├── GenerateMonthlyInvoiceCommand.php<br>│   │   └── GenerateMonthlyInvoiceHandler.php<br>│   └── Queries/<br>│       ├── GetInvoiceBreakdownQuery.php<br>│       └── GetInvoiceBreakdownHandler.php</pre><p>This separation makes it very easy to reason about your application’s use cases at a glance.</p><h4>A simple Command Bus for CQRS</h4><p>To implement CQRS properly in Laravel, you’ll use a <strong>command bus that </strong>takes care of <strong>automatically finding the right handler</strong> for any command or query based on a simple naming convention :</p><ul><li>Command ➔ CommandHandler,</li><li>Query ➔ QueryHandler).</li></ul><p>Here’s a simple version:</p><pre>namespace App\Services;<br><br>use Illuminate\Pipeline\Pipeline;<br><br>class CommandBus<br>{<br>    public function __construct(<br>        protected array $middlewares = []<br>    ) {}<br><br>    public function dispatch(object $command): mixed<br>    {<br>        $handler = $this-&gt;resolveHandler($command);<br><br>        return app(Pipeline::class)<br>            -&gt;send($command)<br>            -&gt;through($this-&gt;middlewares)<br>            -&gt;then(fn ($command) =&gt; $handler-&gt;handle($command));<br>    }<br><br>    protected function resolveHandler(object $command): object<br>    {<br>        $handlerClass = get_class($command) . &#39;Handler&#39;;<br><br>        if (!class_exists($handlerClass)) {<br>            throw new \RuntimeException(&quot;Handler [{$handlerClass}] not found for command &quot; . get_class($command));<br>        }<br><br>        return app($handlerClass);<br>    }<br>}</pre><p>It also gives the flexibility to <strong>add middlewares</strong> around the execution, for example to log, trace, or validate commands before they are actually handled. If you want to use middlewares like logging or tracing:</p><pre>namespace App\Services\Middlewares;<br><br>use Closure;<br><br>class LogCommandExecution<br>{<br>    public function handle(object $command, Closure $next)<br>    {<br>        logger()-&gt;info(&#39;Executing command: &#39; . get_class($command));<br><br>        return $next($command);<br>    }<br>}</pre><p>Then, just register it in your service provider:</p><pre>use App\Services\CommandBus;<br><br>public function register()<br>{<br>    $this-&gt;app-&gt;singleton(CommandBus::class, function () {<br>        return new CommandBus([<br>            // List your middlewares here if needed<br>            \App\Services\Middlewares\LogCommandExecution::class,<br>        ]);<br>    });<br>}</pre><h4>Common structure</h4><p>For <strong>writes</strong>:</p><ul><li>Command: holds the input data</li><li>CommandHandler: contains the business logic</li></ul><p>For <strong>reads</strong>:</p><ul><li>Query: describes the data you want</li><li>QueryHandler: handles the logic and returns a DTO or array</li></ul><h3>Naming your commands and queries</h3><p>Naming matters. In CQRS, <strong>your class names should reflect a business intent</strong>, not a technical action.</p><p>Prefer explicit, intention-revealing names:</p><ul><li>GenerateMonthlyInvoiceCommand</li><li>AssignRoleToUserCommand</li><li>GetInvoiceBreakdownQuery</li></ul><p>Avoid generic names like InvoiceService, Handler, DoStuff, etc.</p><p>Ideally, a non-technical stakeholder should be able to understand what a command does just by reading its name.</p><h3>When should you use CQRS?</h3><p>ou don’t need CQRS everywhere. For simple CRUD, it’s probably overkill. But it becomes very useful when:</p><ul><li>You have rich business rules (state checks, validations, calculations)</li><li>You need to aggregate data before writing</li><li>You want to structure your code around business use cases</li><li>You’re <a href="https://medium.com/@PixelKK/taming-laravel-monoliths-with-modular-architecture-980ff1f4cd08">building modular</a> or DDD-style architectures</li></ul><h3>Real-world example: generating a monthly invoice</h3><p>Let’s take a more realistic example than the usual “create a blog post”: generating a <strong>monthly invoice</strong>.</p><h4>The context</h4><p>At the end of each month, the system must generate an invoice for a customer based on multiple data sources (subscriptions, one-time services, product usage…). Before saving the invoice, it needs to:</p><ul><li>Retrieve all usage records for the month</li><li>Calculate the subtotal, taxes, and possible discounts</li><li>Build invoice line items</li><li>Save everything to the database</li></ul><p><strong>The command</strong> : GenerateMonthlyInvoiceCommand</p><pre>class GenerateMonthlyInvoiceCommand<br>{<br>    public function __construct(<br>        public readonly int $customerId,<br>        public readonly DateTimeInterface $month<br>    ) {}<br>}</pre><p><strong>The handler</strong> :</p><pre>class GenerateMonthlyInvoiceHandler<br>{<br>    public function __construct(<br>        private ConsumptionRepository $consumptions,<br>        private InvoiceRepository $invoices,<br>        private TaxService $taxService,<br>        private DiscountService $discountService,<br>    ) {}<br><br>    public function handle(GenerateMonthlyInvoiceCommand $command): void<br>    {<br>        $items = $this-&gt;consumptions-&gt;forCustomerAndMonth($command-&gt;customerId, $command-&gt;month);<br><br>        if ($items-&gt;isEmpty()) {<br>            throw new DomainException(&#39;No usage to invoice.&#39;);<br>        }<br><br>        $subtotal = $items-&gt;sum(fn($item) =&gt; $item-&gt;price);<br>        $taxes = $this-&gt;taxService-&gt;compute($command-&gt;customerId, $subtotal);<br>        $discount = $this-&gt;discountService-&gt;apply($command-&gt;customerId, $items);<br>        $total = $subtotal + $taxes - $discount;<br><br>        $invoice = new Invoice(<br>            customerId: $command-&gt;customerId,<br>            month: $command-&gt;month,<br>            subtotal: $subtotal,<br>            taxes: $taxes,<br>            discount: $discount,<br>            total: $total<br>        );<br><br>        $invoice-&gt;addLinesFromConsumption($items);<br>        $this-&gt;invoices-&gt;save($invoice);<br>    }<br>}</pre><p><strong>The query </strong>: GetInvoiceBreakdownQuery</p><pre>class GetInvoiceBreakdownQuery<br>{<br>    public function __construct(<br>        public readonly int $customerId,<br>        public readonly DateTimeInterface $month<br>    ) {}<br>}</pre><p><strong>The handler</strong> :</p><pre>class GetInvoiceBreakdownHandler<br>{<br>    public function __construct(private InvoiceRepository $invoices) {}<br><br>    public function handle(GetInvoiceBreakdownQuery $query): InvoiceDTO<br>    {<br>        $invoice = $this-&gt;invoices-&gt;findByCustomerAndMonth($query-&gt;customerId, $query-&gt;month);<br>        return new InvoiceDTO($invoice);<br>    }<br>}</pre><h3>Benefits I noticed in my project</h3><ul><li><strong>Clarity</strong>: command and query names clearly describe business actions</li><li><strong>Isolation</strong>: each handler is easy to test independently</li><li><strong>Organization</strong>: fits perfectly in a modular architecture</li><li><strong>Scalability</strong>: you can easily plug in validation, logging, or events without bloating your controllers</li></ul><h3>Testing handlers</h3><p>CQRS makes unit testing much simpler: each command or query is an isolated unit that you can test without going through a controller or infrastructure.</p><p>Here’s a typical test for a command handler:</p><pre>test(&#39;it generates an invoice with correct totals&#39;) {<br>    $consumptions = collect([<br>        new ConsumptionItem(price: 100),<br>        new ConsumptionItem(price: 200),<br>    ]);<br><br>    $handler = new GenerateMonthlyInvoiceHandler(<br>        new InMemoryConsumptionRepository($consumptions),<br>        new FakeInvoiceRepository(),<br>        new FixedTaxService(20),<br>        new FixedDiscountService(30)<br>    );<br><br>    $handler-&gt;handle(new GenerateMonthlyInvoiceCommand(1, now()));<br><br>    expect(FakeInvoiceRepository::$savedInvoice)-&gt;not-&gt;toBeNull();<br>    expect(FakeInvoiceRepository::$savedInvoice-&gt;total)-&gt;toBe(290); // 300 + 20 - 30<br>}</pre><h3>Conclusion</h3><p>CQRS is a great tool to help structure your code when business logic starts getting more complex (<a href="https://medium.com/@PixelKK/taming-laravel-monoliths-with-modular-architecture-980ff1f4cd08">would fit perfectly in this use case</a>). It makes your intentions explicit, your responsibilities more focused, and your code easier to test.</p><p>You don’t need it everywhere, but when your services start feeling heavy or messy, consider giving it a try. Personally, I wouldn’t go back on larger projects.</p><h3>Bonus: CQRS vs CQS</h3><p>People often confuse CQRS with CQS.</p><ul><li><strong>CQS (Command Query Separation)</strong> is a design principle : a method should either <strong>modify state</strong> (command) or <strong>return data</strong> (query). <strong>NEVER both</strong>.</li><li><strong>CQRS</strong> <strong>(Command Query Responsibility Segregation) </strong>takes this principle further by applying it at the <strong>application level</strong>: separating models, services, and logic for reads and writes.</li></ul><p>So:</p><ul><li>A <strong>CQRS command</strong> can contain some reads (e.g., find a customer before modifying it)</li><li>A <strong>CQS method</strong> must do only one thing: read or write, not both</li></ul><p>CQRS is structural; CQS is behavioral.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d83ec387d926" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular Architecture with Laravel]]></title>
            <link>https://medium.com/@PixelKK/taming-laravel-monoliths-with-modular-architecture-980ff1f4cd08?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/980ff1f4cd08</guid>
            <category><![CDATA[modular-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 14:43:08 GMT</pubDate>
            <atom:updated>2025-05-11T06:43:24.396Z</atom:updated>
            <content:encoded><![CDATA[<p>As Laravel projects grow, maintaining a clean structure becomes increasingly difficult. Controllers pile up, models get bloated, and domain logic starts to leak across unrelated parts of the application. You quickly end up with a monolith that’s hard to scale or reason about.</p><p>That’s where <strong>modular architecture</strong> comes in.</p><h3>Why modular architecture?</h3><p>The core idea is to break your application into<strong> feature-specific modules</strong>, each <strong>responsible</strong> for its own domain logic — authentication, blog, billing, etc. Each module contains its own models, controllers, routes, validation, services, and more.</p><p>This approach offers several key benefits:</p><ul><li><strong>Separation of concerns</strong> — every module owns its logic</li><li><strong>Improved maintainability</strong> — easier to test, extend, or replace parts of the app</li><li><strong>Better scalability</strong> — especially with larger teams or growing business domains</li></ul><blockquote>Modular architecture is particularly useful in mid-to-large-scale applications, where clear functional boundaries exist across features.</blockquote><h3>What we’ll build</h3><p>In this tutorial, I’ll walk you through how to implement a clean modular structure in Laravel using the excellent <a href="https://github.com/nWidart/laravel-modules"><strong>nwidart/laravel-modules</strong></a> package.</p><p>We’ll build two core modules:</p><ul><li><strong>Authentication</strong> — handling registration, login, email verification, logout, etc.</li><li><strong>Blog</strong> — a feature module containing User, Post, and Comment models, with full REST APIs</li></ul><p>Along the way, we’ll cover:</p><ul><li>How to keep modules decoupled but still communicate cleanly</li><li>to centralize authentication logic in the main app</li><li>How to secure all routes from the main app while allowing modules to expose their logic</li><li>How to structure repositories, requests, events, and resources in a scalable and maintainable way</li></ul><blockquote>For the business logic and API structure, I’ll build on top of what I introduced in <a href="https://medium.com/@PixelKK/how-to-build-a-rest-api-with-laravel-beginners-guide-fff06c270ee9">this previous article</a>, adapting it to a modular architecture — so it might be worth giving it a quick read first.</blockquote><h3>Getting Started: Project Setup and Docker Configuration</h3><p>Before jumping into modularization, we need a solid Laravel base to work on — ideally with Docker so everything is isolated and reproducible across environments.</p><p>If you’re not familiar with Docker or want a ready-to-go setup for Laravel, I recommend checking out this article:</p><p>👉 <a href="https://medium.com/@PixelKK/getting-started-with-laravel-projects-using-docker-my-basic-configuration-eb86d795dfa0">Getting Started with Laravel Projects Using Docker — My Basic Configuration</a></p><p>It walks through a minimal and efficient Docker setup using:</p><ul><li>PHP-FPM container</li><li>Nginx for web server</li><li>MySQL/MariaDB for database</li><li>Mailhog for local email testing</li><li>and volume bindings to keep everything in sync</li></ul><p>Once your Docker environment is up and Laravel is running (you can use the make laravel-install) in the container, we can move to the modular part of the project.</p><blockquote>I’ve made the full implementation of this tutorial available here: <a href="https://github.com/mouize/demo-modular-architecture">https://github.com/mouize/demo-modular-architecture</a></blockquote><h3>1. Install the nwidart/laravel-modules package</h3><p>We’ll use the excellent <a href="https://github.com/nWidart/laravel-modules">nwidart/laravel-modules</a> package to structure our app into independent feature modules.</p><p>Install it via Composer:</p><pre>composer require nwidart/laravel-modules</pre><p>Then publish the config file:</p><pre>php artisan vendor:publish --provider=&quot;Nwidart\Modules\LaravelModulesServiceProvider&quot;</pre><p>To ensure Composer can autoload our modules, update your composer.json with:</p><pre>&quot;autoload&quot;: {<br>    &quot;psr-4&quot;: {<br>        &quot;Modules\\&quot;: &quot;Modules/&quot;<br>    }<br>},<br>&quot;extra&quot;: {<br>    &quot;merge-plugin&quot;: {<br>        &quot;include&quot;: [<br>            &quot;Modules/*/composer.json&quot;<br>        ]<br>    }<br>}</pre><p>And run:</p><pre>composer dump-autoload</pre><blockquote>You can also customize how modules are generated by editing config/modules.php — for example, under the generator section, you can define which folders or files should be created by default for each module.</blockquote><h3>2. Setting up the Authentication Module</h3><p>The first feature we’re going to modularize is authentication — one of the most critical and commonly reused parts of any application.</p><p>We’ll use Laravel Sanctum for token-based authentication, and organize the entire auth logic (registration, login, logout, email verification) inside a dedicated <strong>Authentication</strong> module.</p><p>But before diving into code, let’s understand the reasoning behind it.</p><h4>Why isolate authentication into a module?</h4><p>Authentication often touches a lot of parts in an app (user creation, email verification, session/token management, etc.), so it makes sense to extract it into its own self-contained domain.</p><p>By doing this:</p><ul><li>We <strong>reduce coupling</strong> between authentication logic and the rest of the app</li><li>We can <strong>reuse or replace</strong> the module easily in other Laravel projects</li><li>We keep things organized and scalable — one module, one responsibility</li></ul><h4>Create the authentication module</h4><pre>php artisan module:make Authentication</pre><p>This scaffolds a fully isolated folder structure under Modules/Authentication, including space for models, controllers, routes, requests, events, etc.</p><h4>Create the AuthController</h4><pre>namespace Modules\Authentication\Http\Controllers;<br><br>use App\Http\Controllers\Controller;<br>use Illuminate\Http\JsonResponse;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Hash;<br>use Illuminate\Support\Facades\Event;<br>use Modules\Authentication\Http\Requests\RegisterRequest;<br>use Modules\Authentication\Http\Requests\LoginRequest;<br>use Modules\Authentication\Contracts\UserRepositoryInterface;<br>use Modules\Authentication\Events\UserRegistered;<br>use Modules\Authentication\Events\UserVerified;<br><br>class AuthController extends Controller<br>{<br>    public function __construct(protected UserRepositoryInterface $userRepository) {}<br><br>    public function register(RegisterRequest $request): JsonResponse<br>    {<br>        $user = $this-&gt;userRepository-&gt;register([<br>            &#39;name&#39; =&gt; $request-&gt;validated(&#39;name&#39;),<br>            &#39;email&#39; =&gt; $request-&gt;validated(&#39;email&#39;),<br>            &#39;password&#39; =&gt; Hash::make($request-&gt;validated(&#39;password&#39;),<br>        ]);<br><br>        Event::dispatch(new UserRegistered($user));<br><br>        return response()-&gt;json([<br>            &#39;message&#39; =&gt; &#39;Account created successfully. Please check your email to verify your account.&#39;,<br>        ], 201);<br>    }<br><br>    public function verify(Request $request): JsonResponse<br>    {<br>        $user = $this-&gt;userRepository-&gt;findOrFail($request-&gt;route(&#39;id&#39;));<br><br>        if (! hash_equals((string) $request-&gt;route(&#39;hash&#39;), sha1($user-&gt;getEmail()))) {<br>            return response()-&gt;json([&#39;message&#39; =&gt; &#39;Invalid verification link&#39;], 400);<br>        }<br><br>        Event::dispatch(new UserVerified($user));<br><br>        return response()-&gt;json([&#39;message&#39; =&gt; &#39;Email verified successfully&#39;]);<br>    }<br><br>    public function login(LoginRequest $request): JsonResponse<br>    {<br>        $user = $this-&gt;userRepository-&gt;getUserByEmail($request-&gt;validated(&#39;email&#39;));<br><br>        if (! $user || ! Hash::check($request-&gt;validated(&#39;password&#39;), $user-&gt;getPassword())) {<br>            return response()-&gt;json([&#39;message&#39; =&gt; &#39;Invalid credentials&#39;], 401);<br>        }<br><br>        $token = $user-&gt;createToken(&#39;auth_token&#39;);<br><br>        return response()-&gt;json([<br>            &#39;access_token&#39; =&gt; $token-&gt;plainTextToken,<br>            &#39;token_type&#39; =&gt; &#39;Bearer&#39;,<br>        ]);<br>    }<br><br>    public function logout(Request $request): JsonResponse<br>    {<br>        $request-&gt;user()-&gt;tokens()-&gt;delete();<br><br>        return response()-&gt;json([&#39;message&#39; =&gt; &#39;Successfully logged out&#39;]);<br>    }<br>}</pre><h4>Add FormRequest validation</h4><p>To keep our controller clean and follow Laravel best practices, we use <strong>FormRequest classes</strong> to validate the inputs.</p><pre>php artisan module:make-request RegisterRequest Authentication<br>php artisan module:make-request LoginRequest Authentication</pre><p>Then define rules in each request:</p><pre>//Modules/Authentication/Http/Requests/RegisterRequest.php<br>public function rules(): array<br>{<br>    return [<br>        &#39;name&#39; =&gt; [&#39;required&#39;, &#39;string&#39;],<br>        &#39;email&#39; =&gt; [&#39;required&#39;, &#39;email&#39;, &#39;unique:users,email&#39;],<br>        &#39;password&#39; =&gt; [&#39;required&#39;, &#39;min:8&#39;],<br>    ];<br>}<br><br>//Modules/Authentication/Http/Requests/LoginRequest.php<br>public function rules(): array<br>{<br>    return [<br>        &#39;email&#39; =&gt; [&#39;required&#39;, &#39;email&#39;],<br>        &#39;password&#39; =&gt; [&#39;required&#39;],<br>    ];<br>}</pre><h4>Define contracts to decouple logic</h4><p>To keep our module independent from the actual User implementation, we rely on <strong>interfaces</strong>.</p><p>This allows the main application to define how users are created, authenticated, and managed — while the module simply expects any class that fulfills the contract.</p><p>Create two interfaces inside your module:</p><pre>php artisan module:make-interface UserInterface Authentication<br>php artisan module:make-interface UserRepositoryInterface Authentication</pre><pre>namespace Modules\Authentication\Contracts;<br><br>interface UserInterface<br>{<br>    public function getId(): int;<br>    public function getEmail(): string;<br>    public function getPassword(): string;<br>    public function createToken(string $name);<br>}</pre><pre>namespace Modules\Authentication\Contracts;<br><br>interface UserRepositoryInterface<br>{<br>    public function register(array $data): UserInterface;<br>    public function getUserByEmail(string $email): ?UserInterface;<br>    public function findOrFail(int $id): UserInterface;<br>}</pre><h4>Use events to externalize side-effects</h4><p>Instead of triggering things like email notifications or verification logic directly inside the controller, we use <strong>events</strong> to handle side effects.</p><p>This gives us:</p><ul><li>Clear separation of responsibilities</li><li>Flexibility to change what happens after registration without touching the controller</li></ul><pre>php artisan module:make-event UserRegistered Authentication<br>php artisan module:make-event UserVerified Authentication</pre><p>Define them like so:</p><pre>namespace Modules\Authentication\Events;<br><br>use Illuminate\Foundation\Events\Dispatchable;<br>use Illuminate\Queue\SerializesModels;<br>use Modules\Authentication\Interfaces\UserInterface;<br><br>class UserRegistered<br>{<br>    use Dispatchable, SerializesModels;<br><br>    /**<br>     * Create a new event instance.<br>     */<br>    public function __construct(public UserInterface $user) {}<br>}</pre><pre>use Illuminate\Foundation\Events\Dispatchable;<br>use Illuminate\Queue\SerializesModels;<br>use Modules\Authentication\Interfaces\UserInterface;<br><br>class UserVerified<br>{<br>    use Dispatchable, SerializesModels;<br><br>    /**<br>     * Create a new event instance.<br>     */<br>    public function __construct(public UserInterface $user) {}<br>}</pre><h3>3. Creating the Blog Module</h3><p>Now that our authentication module is in place, let’s move on to building a second module — the <strong>Blog</strong> module.</p><p>This will represent a real business feature and give us the opportunity to organize models, resources, relationships, validation, and repositories in a modular way.</p><pre>php artisan module:make Blog</pre><p>Let’s generate our User, Post, and Comment models using the built-in Nwidart generator:</p><pre>php artisan module:make-model User Blog -frRc<br>php artisan module:make-model Post Blog -frRc<br>php artisan module:make-model Comment Blog -frRc</pre><p><a href="https://github.com/mouize/demo-modular-architecture/tree/main/app/Modules/Blog/app/Models">We can now define for each model</a> the relationships and fillable attributes inside each one.</p><p>The -frRc flags we used when generating the models gave us a solid base: eloquent resources, form requests, and RESTful controllers were all scaffolded automatically.</p><p>Now we just need to fill in the logic to bring it all together.</p><h4>Migrations</h4><p>Create the corresponding migrations in a folder stubs/migrations <a href="https://github.com/mouize/demo-modular-architecture/tree/main/app/Modules/Blog/stubs/migrations">as shown here.</a> (will be discussed deeply in a next section)</p><h4>Using Spatie Query Builder for Clean &amp; Flexible Queries</h4><p>To keep our controllers clean and make our API flexible for consumers, we use <a href="https://github.com/spatie/laravel-query-builder">Spatie Query Builder</a>.</p><p>It allows us to build powerful filters, includes, and sorts with zero extra logic in the controller. All of that is handled inside the repository layer.</p><pre>composer require spatie/laravel-query-builder</pre><p>Each module has its own composer.json, so we also need to add the package there:</p><pre>#Modules/Blog/composer.json<br>&quot;require&quot;: {<br>    &quot;spatie/laravel-query-builder&quot;: &quot;*&quot; //You can set a specific version depending on your needs<br>}</pre><p>Then, regenerate the autoloader:</p><pre>composer dump-autoload</pre><h4>Repositories: Centralizing Data Access</h4><p>We can generate our repositories now:</p><pre>php artisan module:make-repository UserRepository Blog<br>php artisan module:make-repository PostRepository Blog<br>php artisan module:make-repository CommentRepository Blog</pre><p><a href="https://github.com/mouize/demo-modular-architecture/tree/main/app/Modules/Blog/app/Repositories">Let’s complete them</a> to encapsulate all the logic for querying and persisting data.</p><h4>Http logics</h4><p><a href="https://github.com/mouize/demo-modular-architecture/tree/main/app/Modules/Blog/app/Http/Controllers">RESTful controllers</a>, f<a href="https://github.com/mouize/demo-modular-architecture/tree/main/app/Modules/Blog/app/Http/Requests">orm requests</a>, <a href="https://github.com/mouize/demo-modular-architecture/tree/main/app/Modules/Blog/app/Http/Resources">eloquent resources</a> were also scaffolded, let’s plug them into the repositories and handle basic CRUD operations as shown here.</p><h3>4. Publishing Module Routes &amp; Migrations</h3><p>By design, modules should stay <strong>generic and reusable</strong>. That’s why we avoid hardcoding things like route prefixes or middleware inside the module.</p><p>Instead, we let the <strong>main application decide</strong>:</p><ul><li>how to group or secure the routes</li><li>how to customize the migration structure if needed</li></ul><p>To achieve that, we make our <strong>routes and migrations publishable</strong>.</p><h4>Making routes publishable</h4><p>In both the Authentication and Blog modules, define routes in a simple way — no middleware, no prefix:</p><pre>//Modules/Authentication/Routes/api.php<br>use Illuminate\Support\Facades\Route;<br>use Modules\Authentication\Http\Controllers\AuthController;<br><br>Route::post(&#39;register&#39;, [AuthController::class, &#39;register&#39;]);<br>Route::post(&#39;login&#39;, [AuthController::class, &#39;login&#39;]);<br>Route::post(&#39;logout&#39;, [AuthController::class, &#39;logout&#39;]);<br>Route::get(&#39;verify/{id}/{hash}&#39;, [AuthController::class, &#39;verify&#39;]);</pre><pre>//Modules/Blog/Routes/api.php<br>use Illuminate\Support\Facades\Route;<br>use Modules\Blog\Http\Controllers\UserController;<br>use Modules\Blog\Http\Controllers\PostController;<br>use Modules\Blog\Http\Controllers\CommentController;<br><br>Route::apiResource(&#39;users&#39;, UserController::class);<br>Route::apiResource(&#39;posts&#39;, PostController::class);<br>Route::apiResource(&#39;comments&#39;, CommentController::class);</pre><blockquote>By avoiding hardcoded route groups, modules stay clean and composable — the main app is free to apply auth, prefixes, or rate limiting globally.</blockquote><p>Then in your module service provider, add:</p><pre>//Modules/Authentication/app/Providers/AuthenticationServiceProvider<br>$this-&gt;publishes([<br>    __DIR__.&#39;/../../routes/api.php&#39; =&gt; base_path(&#39;routes/modules/Authentication/api.php&#39;),<br>], &#39;authentication-routes&#39;);</pre><pre>//Modules/Blog/app/Providers/BlogServiceProvider<br>$this-&gt;publishes([<br>    __DIR__.&#39;/../../routes/api.php&#39; =&gt; base_path(&#39;routes/modules/Blog/api.php&#39;),<br>], &#39;blog-routes&#39;);</pre><p>From the main app, you can now publish and control the routes:</p><pre>php artisan vendor:publish --tag=authentication-routes<br>php artisan vendor:publish --tag=blog-routes</pre><p>You’ll get fully editable copies under routes/modules/Blog/api.php and routes/modules/Authentication/api.php.</p><p>Once published, the app can load these routes with proper middleware and prefixing.</p><p>(We’ll see that in the next section.)</p><h4>Making migrations publishable</h4><p>Same idea for migrations. If the app needs to add extra columns or adapt table structures, it can override the module’s migrations.</p><p>In the same service providers:</p><pre>//Modules/Authentication/app/Providers/AuthenticationServiceProvider<br>$this-&gt;publishes([<br>    __DIR__.&#39;/../../stubs/migrations&#39; =&gt; database_path(&#39;migrations&#39;),<br>], &#39;authentication-migrations&#39;);</pre><pre>//Modules/Blog/app/Providers/BlogServiceProvider<br>$this-&gt;publishes([<br>    __DIR__.&#39;/../../stubs/migrations&#39; =&gt; database_path(&#39;migrations&#39;),<br>], &#39;blog-migrations&#39;);</pre><blockquote><strong>Important:</strong> We moved the migrations to the stubs/migrations folder to prevent them from being executed during a migrate command unless they are explicitly published first.</blockquote><p>Then publish them with:</p><pre>php artisan vendor:publish --tag=authentication-migrations<br>php artisan vendor:publish --tag=blog-migrations</pre><p>You’ll get fully editable copies under database/migrations</p><h3>5. Orchester Modules from the Main Application</h3><p>Now that our modules are structured and publish their routes and migrations, the main application becomes the central <strong>orchestrator</strong>. It will:</p><ul><li>Connect the app’s User model to the Authentication module</li><li>Implement the UserRepositoryInterface and UserInterface</li><li>Secure and load the module routes dynamically</li><li>Listen to events (like UserRegistered) and decide how to react</li></ul><h4>Create the main User model</h4><p>This model lives in the app and <strong>extends</strong> the User model from the Blog module:</p><pre>namespace App\Models;<br><br>use App\Mail\CustomVerifyEmail;<br>use Illuminate\Auth\Authenticatable;<br>use Illuminate\Auth\MustVerifyEmail;<br>use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;<br>use Laravel\Sanctum\HasApiTokens;<br>use Illuminate\Notifications\Notifiable;<br>use Modules\Authentication\Interfaces\UserInterface;<br>use Modules\Blog\Models\User as BlogUser;<br><br>class User extends BlogUser implements UserInterface, AuthenticatableContract<br>{<br>    use HasApiTokens, Notifiable, Authenticatable, MustVerifyEmail;<br><br>    protected $fillable = [&#39;name&#39;, &#39;email&#39;, &#39;password&#39;];<br><br>    public function getId(): int<br>    {<br>        return $this-&gt;id;<br>    }<br><br>    public function getEmail(): string<br>    {<br>        return $this-&gt;email;<br>    }<br><br>    public function getPassword(): string<br>    {<br>        return $this-&gt;password;<br>    }<br><br>    public function sendEmailVerificationNotification(): void<br>    {<br>        $this-&gt;notify(new CustomVerifyEmail);<br>    }<br>}</pre><blockquote>This model handles authentication and implements the interface expected by the Authentication module.</blockquote><h4>Configure Laravel to use this User model</h4><p>In config/auth.php:</p><pre>&#39;providers&#39; =&gt; [<br>    &#39;users&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;eloquent&#39;,<br>        &#39;model&#39; =&gt; App\Models\User::class,<br>    ],<br>],</pre><h4>Implement the UserRepository</h4><pre>namespace App\Repository;<br><br>use App\Models\User;<br>use Modules\Authentication\Interfaces\UserInterface;<br>use Modules\Authentication\Interfaces\UserRepositoryInterface;<br>use Modules\Blog\Repositories\UserRepository as BlogUserRepository;<br><br>class UserRepository extends BlogUserRepository implements UserRepositoryInterface<br>{<br>    protected string $model = User::class;<br><br>    public function register(array $data): UserInterface<br>    {<br>        return $this-&gt;model::create($data);<br>    }<br><br>    public function getUserByEmail(string $email): ?UserInterface<br>    {<br>        return $this-&gt;model::where(&#39;email&#39;, $email)-&gt;first();<br>    }<br><br>    public function findOrFail(int $id): UserInterface<br>    {<br>        return $this-&gt;model::findOrFail($id);<br>    }<br>}</pre><p>Then bind the interface in your AppServiceProvider:</p><pre>use Modules\Authentication\Contracts\UserRepositoryInterface;<br>use App\Repositories\UserRepository;<br><br>public function register()<br>{<br>    $this-&gt;app-&gt;bind(UserRepositoryInterface::class, UserRepository::class);<br>}</pre><h4>Listen to events</h4><p>Create listeners for the events dispatched in the Authentication module.</p><pre>namespace App\Listeners;<br><br>use Modules\Authentication\Events\UserRegistered;<br><br>class SendEmailVerificationNotification<br>{<br>    public function handle(UserRegistered $event): void<br>    {<br>        $event-&gt;user-&gt;sendEmailVerificationNotification();<br>    }<br>}</pre><pre>namespace App\Listeners;<br><br>use Modules\Authentication\Events\UserVerified;<br><br>class MarkEmailAsVerified<br>{<br>    public function handle(UserVerified $event): void<br>    {<br>        $event-&gt;user-&gt;markEmailAsVerified();<br>    }<br>}</pre><p>Register them in EventServiceProvider (if needed):</p><pre>use Modules\Authentication\Events\UserRegistered;<br>use Modules\Authentication\Events\UserVerified;<br><br>protected $listen = [<br>    UserRegistered::class =&gt; [<br>        \App\Listeners\SendEmailVerificationNotification::class,<br>    ],<br>    UserVerified::class =&gt; [<br>        \App\Listeners\MarkEmailAsVerified::class,<br>    ],<br>];</pre><h4>Secure routes</h4><p>Create a new service provider like ModuleRouteServiceProvider:</p><pre>namespace App\Providers;<br><br>use Illuminate\Support\Facades\Route;<br>use Illuminate\Support\ServiceProvider;<br>use Nwidart\Modules\Facades\Module;<br><br>class ModuleRouteServiceProvider extends ServiceProvider<br>{<br>    public function boot(): void<br>    {<br>        foreach (Module::allEnabled() as $module) {<br>            $name = $module-&gt;getName();<br>            $path = base_path(&quot;routes/modules/{$name}/api.php&quot;);<br><br>            if (file_exists($path)) {<br>                Route::prefix(&#39;api&#39;)<br>                    -&gt;name(&#39;api.&#39;)<br>                    -&gt;group($path);<br>            }<br>        }<br>    }<br>}</pre><blockquote>If needed, declare this new ServiceProvider in bootstrap/providers</blockquote><p>Once the module routes are published (e.g. routes/modules/Blog/api.php), the main app can customize them freely — including applying authentication middleware.</p><p>For example, in the Blog module:</p><pre>use Illuminate\Support\Facades\Route;<br>use Modules\Blog\Http\Controllers\PostController;<br>use Modules\Blog\Http\Controllers\UserController;<br>use Modules\Blog\Http\Controllers\CommentController;<br><br>Route::middleware(&#39;auth:sanctum&#39;)-&gt;group(function () {<br>    Route::apiResource(&#39;users&#39;, UserController::class);<br>    Route::apiResource(&#39;posts&#39;, PostController::class);<br>    Route::apiResource(&#39;comments&#39;, CommentController::class);<br>});</pre><p>And for the Authentication module:</p><pre>use Illuminate\Support\Facades\Route;<br>use Modules\Authentication\Http\Controllers\AuthController;<br><br>Route::post(&#39;register&#39;, [AuthenticationController::class, &#39;register&#39;])<br>    -&gt;name(&#39;register&#39;);<br>Route::post(&#39;login&#39;, [AuthenticationController::class, &#39;login&#39;])<br>    -&gt;name(&#39;login&#39;);<br>Route::middleware(&#39;signed&#39;)<br>    -&gt;get(&#39;/email/verify/{id}/{hash}&#39;, [AuthenticationController::class, &#39;verify&#39;])<br>    -&gt;name(&#39;verification.verify&#39;);</pre><blockquote>This gives you <strong>maximum control</strong> over each module’s security behavior, without needing to maintain a custom route loader.</blockquote><p>Your app now orchestrates everything:</p><ul><li>It owns the User logic</li><li>Secures and loads module routes dynamically</li><li>Handles auth-specific events</li><li>Keeps the modules decoupled and reusable</li></ul><h3>And Voilà</h3><p>Modular architecture brings clarity, separation of concerns, and long-term maintainability to Laravel projects — especially when things start to grow.</p><p>By leveraging <a href="https://github.com/nWidart/laravel-modules">nwidart/laravel-modules</a>, we’ve been able to:</p><ul><li>Split our application into <strong>clearly defined domains</strong></li><li>Keep modules <strong>independent and reusable</strong></li><li>Centralize responsibilities like <strong>authentication, route security, and event handling</strong> in the main app</li><li>Maintain <strong>clean API logic</strong> using repositories, resources, FormRequests, and Spatie Query Builder</li></ul><p>This structure is particularly useful in real-world teams, where different developers work on different parts of the system, or where features evolve independently over time.</p><h3>Bonus: What about Domain-Driven Design (DDD)?</h3><p>Modular architecture is often confused with DDD — and while the two can overlap, they’re not the same.</p><ul><li>Modular architecture is about <strong>technical organization</strong>: splitting your code by feature to make it more maintainable.</li><li>DDD is about <strong>business modeling</strong>: building your code around the language and rules of your domain.</li></ul><p>You can absolutely use both together — in fact, modules are a great place to implement bounded contexts and aggregates if you want to go deeper into DDD later on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=980ff1f4cd08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a REST API with Laravel (Beginner Guide — Part 3): Using Api Platform]]></title>
            <link>https://medium.com/@PixelKK/how-to-build-a-rest-api-with-laravel-beginner-guide-part-3-using-api-platform-044ae89dd87a?source=rss-f07f7b3d3e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/044ae89dd87a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[api-platform]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[PixelKK]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 15:31:42 GMT</pubDate>
            <atom:updated>2025-03-24T15:33:21.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build a REST API with Laravel (Beginner Guide — Part 3): Using Api Platform</h3><p><a href="https://medium.com/@PixelKK/how-to-build-a-rest-api-with-laravel-beginners-guide-fff06c270ee9">In the first article of this series</a>, we went through the entire process of building a REST API with Laravel from scratch. We covered defining models, setting up controllers, and manually handling requests and responses. While this approach gives you full control, it can also be tedious and repetitive.</p><p>In this article, we’ll see how to simplify the process by using <a href="https://api-platform.com/docs/laravel/"><strong>API Platform</strong></a>. This bundle provides a ready-to-use framework for building APIs with Laravel, making it much easier and faster to create CRUD operations and expose resources. Let’s dive in and see how API Platform can make your life easier!</p><h3>Why Use API Platform with Laravel?</h3><p><a href="https://api-platform.com/docs/laravel/">API Platform</a> is a powerful framework designed to build REST and GraphQL APIs with ease. It offers:</p><ul><li>Automatic CRUD generation for models.</li><li>Pagination, filtering, and sorting out of the box.</li><li>Built-in support for OpenAPI documentation.</li><li>A simplified way to expose your data as an API.</li></ul><h3>1. Setting Up Laravel and Database Configuration</h3><p>If you are interested in containerizing your Laravel project using Docker, you can check out my article here: <a href="https://medium.com/@saad.mouizina/getting-started-with-laravel-projects-using-docker-my-basic-configuration-eb86d795dfa0">Getting Started with Laravel Projects Using Docker</a>.</p><p>For the latest installation instructions, refer to the official Laravel documentation: <a href="https://laravel.com/docs/11.x/installation#creating-a-laravel-project">Creating a Laravel Project</a>.</p><h3>2. Installation API Platform</h3><p><a href="https://api-platform.com/docs/laravel/#installing-api-platform">Follow the instruction given in documentation:</a></p><pre>composer require api-platform/laravel<br>php artisan api-platform:install</pre><h3>3. Defining Your Models</h3><p><a href="https://medium.com/@PixelKK/how-to-build-a-rest-api-with-laravel-beginners-guide-fff06c270ee9">You can follow same instructions (2. Generate Models with Migrations and 3. Define Relationships in Models) from the previous article</a></p><h3>4. Creating API Resources</h3><p>API Platform allows you to quickly expose your models as API Resources. Simply add the ApiResource attribute to your model classes.</p><p>Dxample with Post model :</p><pre>namespace App\Models;<br><br>use ApiPlatform\Metadata\ApiResource;<br>use Illuminate\Database\Eloquent\Model;<br><br>#[ApiResource]<br>class Post extends Model<br>{<br>    ...<br>}</pre><p><strong>And Voilà.</strong></p><blockquote>Open http://127.0.0.1:8000/api/, your API is already active and documented !</blockquote><h3>5. Add some Extra configurations</h3><h4>Pagination</h4><p><a href="https://api-platform.com/docs/laravel/#paginating-data">API Platform supports pagination out of the box</a>. To customize the pagination settings, you can update the config/api-platform.php file. For example, to set the default items per page:</p><pre>&#39;resources&#39; =&gt; [<br>    &#39;pagination_enabled&#39; =&gt; true,<br>    &#39;items_per_page&#39; =&gt; 10,  // Default number of items per page<br>],</pre><p>When you make a request to your API, you can specify the page query parameter : GET /api/posts?page=2</p><p>Alternatively, you can set the pagination directly on the ApiResource of the Model :</p><pre>namespace App\Models;<br><br>use ApiPlatform\Metadata\ApiResource;<br>use ApiPlatform\Metadata\GetCollection;<br>use ApiPlatform\Laravel\Eloquent\Filter\PartialSearchFilter;<br>use ApiPlatform\Laravel\Eloquent\Filter\OrderFilter;<br>use Illuminate\Database\Eloquent\Model;<br><br>#[ApiResource(<br>  paginationItemsPerPage: 10<br>)]<br>class Post extends Model<br>{<br>    ...<br>}</pre><h4>Query Parameters (Filtering &amp; Sorting)</h4><p><a href="https://api-platform.com/docs/laravel/filters/">API Platform provides powerful filtering and sorting mechanisms</a>. You can define filters directly in your model using attributes. For example with Post:</p><pre>namespace App\Models;<br><br>use ApiPlatform\Metadata\ApiResource;<br>use ApiPlatform\Metadata\GetCollection;<br>use ApiPlatform\Laravel\Eloquent\Filter\PartialSearchFilter;<br>use ApiPlatform\Laravel\Eloquent\Filter\OrderFilter;<br>use Illuminate\Database\Eloquent\Model;<br><br>#[ApiResource]<br>#[QueryParameter(key: &#39;title&#39;, filter: PartialSearchFilter::class)]<br>#[QueryParameter(key: &#39;sort[:title]&#39;, filter: OrderFilter::class)]<br>class Post extends Model<br>{<br>    ...<br>}</pre><p>When you make a request to your API, you can specify the partial filter and the sort as defined, in the query parameters : GET /api/posts?title=look&amp;order[title]=asc</p><h4>Format Output</h4><p>API Platform can return data in various formats. By default, it supports application/ld+json format.</p><p>If you want to accept and return data as plain JSON or any other format, make sure to <a href="https://api-platform.com/docs/laravel/#content-negotiation">update your config/api-platform.php</a></p><h3>6. Securing Routes with Laravel Sanctum</h3><p>You can secure your API routes with <strong>Laravel Sanctum</strong> just like we did <a href="https://medium.com/@PixelKK/how-to-build-a-rest-api-with-laravel-part-2-authentication-with-sanctum-e88ce1a80440">in the previous article</a>.</p><p>To secure a route <a href="https://api-platform.com/docs/laravel/security/#authentication">with API Platform</a>, just add the middleware to the ApiResource attribute :</p><pre>namespace App\Models;<br><br>use ApiPlatform\Metadata\ApiResource;<br>use Illuminate\Database\Eloquent\Model;<br><br>#[ApiResource(<br>    middleware: [&#39;auth:sanctum&#39;]<br>)]<br>class Post extends Model<br>{<br>    ...<br>}</pre><h3>Testing the API</h3><h4>Pre-requisite:</h4><p>If you want to test the API using Docker, you can follow my tutorial here: <a href="https://medium.com/@PixelKK/getting-started-with-laravel-projects-using-docker-my-basic-configuration-eb86d795dfa0">Getting Started with Laravel Projects Using Docker</a>.</p><p>You can find a <a href="https://github.com/mouize/demo-platform-api/tree/main/app/docs">postman collection here</a></p><h4>Register a New User</h4><pre>curl -X POST http://127.0.0.1:8000/api/register \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;name&quot;: &quot;John Doe&quot;, &quot;email&quot;: &quot;john@example.com&quot;, &quot;password&quot;: &quot;secret&quot;}&#39;</pre><p>This should return a message instructing the user to check their email for verification.</p><p>Check the email sent to the registered user (in MailHog if running locally). The verification link will look like:</p><pre>http://127.0.0.1:8000/api/email/verify/{id}/{hash}</pre><p>If successful, it should return:</p><pre>{&quot;message&quot;: &quot;Email verified successfully&quot;}</pre><h4>Log in with the User</h4><pre>curl -X POST http://127.0.0.1:8000/api/login \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;email&quot;: &quot;john@example.com&quot;, &quot;password&quot;: &quot;secret&quot;}&#39;</pre><p>This should return an access token:</p><pre>{<br>    &quot;access_token&quot;: &quot;your_generated_token&quot;,<br>    &quot;token_type&quot;: &quot;Bearer&quot;<br>}</pre><h4>Access a Protected Route</h4><p>You should be able to access to any protected route now by adding the Bearer Token in your request header</p><pre>curl -X GET http://127.0.0.1:8000/api/posts \<br>     -H &quot;Authorization: Bearer your_generated_token&quot;</pre><h4>Create a new Post:</h4><pre>curl -X POST http://127.0.0.1:8000/api/posts \<br>     -H &quot;Content-Type: application/ld+json&quot; \<br>     -d &#39;{<br>    &quot;title&quot;: &quot;my post&quot;,<br>    &quot;content&quot;: &quot;super nice one tho&quot;,<br>    &quot;user&quot;: &quot;/api/users/1&quot;<br>}&#39;</pre><h3>Conclusion</h3><p>Using API Platform in Laravel makes it incredibly easy to build robust APIs with minimal configuration. And by combining it with Laravel Sanctum, you can ensure your API is secure without much effort. Take a deep look into <a href="https://api-platform.com/docs/laravel/">API Platform documentation</a> for more features!</p><p>Github link : <a href="https://github.com/mouize/demo-platform-api">https://github.com/mouize/demo-platform-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=044ae89dd87a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>