From fbacb0c9a1f12f22dbfeabdbc30e6b4ee6e85911 Mon Sep 17 00:00:00 2001 From: Parsa Aghayi Date: Fri, 2 Oct 2026 09:34:53 -0400 Subject: [PATCH] Expand blog to 36 mirrored posts with deepened sections and page-turn links - Six new topic pairs (EN+FA): TypeScript advanced patterns, SQL indexes, Git branching/reviews, TDD, clean architecture in Laravel, browser page load - Every existing post gains Key takeaways + FAQ sections in both languages - New engineering-practices category pair and database/git/testing tag pairs - Single-post API now returns same-language previous_post/next_post links --- .../Controllers/Api/Blog/PostController.php | 34 + .../seeders/Blog/RealBlogContentSeeder.php | 1300 +++++++++++++++++ tests/Feature/Blog/PostTest.php | 25 +- .../Blog/RealBlogContentSeederTest.php | 27 +- 4 files changed, 1377 insertions(+), 9 deletions(-) diff --git a/app/Http/Controllers/Api/Blog/PostController.php b/app/Http/Controllers/Api/Blog/PostController.php index d73cdc5..b80b003 100644 --- a/app/Http/Controllers/Api/Blog/PostController.php +++ b/app/Http/Controllers/Api/Blog/PostController.php @@ -82,9 +82,43 @@ class PostController extends Controller ->sortByDesc('published_at') ->take(5); + // Plainly named page-turn links, always inside the reader's language so + // the previous/next navigation never crosses the EN/FA mirror. + $siblings = Post::with(['category', 'tags', 'author']) + ->byLanguage($postLang) + ->where('id', '!=', $post->id); + + $previousPost = (clone $siblings) + ->where( + fn ($q) => $q->where('published_at', '>', $post->published_at) + ->orWhere( + fn ($q2) => $q2 + ->where('published_at', '=', $post->published_at) + ->where('id', '>', $post->id) + ) + ) + ->orderByDesc('published_at') + ->orderByDesc('id') + ->first(); + + $nextPost = (clone $siblings) + ->where( + fn ($q) => $q->where('published_at', '<', $post->published_at) + ->orWhere( + fn ($q2) => $q2 + ->where('published_at', '=', $post->published_at) + ->where('id', '<', $post->id) + ) + ) + ->orderBy('published_at') + ->orderBy('id') + ->first(); + return response()->json([ 'post' => new PostResource($post), 'related_posts' => PostResource::collection($relatedPosts), + 'previous_post' => $previousPost ? new PostResource($previousPost) : null, + 'next_post' => $nextPost ? new PostResource($nextPost) : null, ], 200); } diff --git a/database/seeders/Blog/RealBlogContentSeeder.php b/database/seeders/Blog/RealBlogContentSeeder.php index 98b682a..31a71df 100644 --- a/database/seeders/Blog/RealBlogContentSeeder.php +++ b/database/seeders/Blog/RealBlogContentSeeder.php @@ -59,6 +59,8 @@ class RealBlogContentSeeder extends Seeder ['name' => 'Web Performance & SEO', 'slug' => 'web-performance-seo', 'description' => 'Core Web Vitals, technical SEO and the measurements that make interfaces feel instant, stay findable and rank.', 'short_description' => 'Speed, Core Web Vitals and technical SEO that move rankings.'], // Persian + ['name' => 'Engineering Practices', 'slug' => 'engineering-practices', 'description' => 'Testing, clean code, version control and the habits that keep a codebase healthy as a team grows.', 'short_description' => 'Testing, clean code and the habits that keep codebases healthy.'], + ['name' => 'مهندسی نرمافزار', 'slug' => 'engineering-practices-fa', 'description' => 'تست، کد تمیز، کنترل نسخه و عادت‌هایی که در رشد تیم، سلامت کد را حفظ می‌کنند.', 'short_description' => 'تست، کد تمیز و عادت‌های سالم نگه‌داشتن کد.'], ['name' => 'توسعه فرانت‌اند', 'slug' => 'frontend-fa', 'description' => 'مقاله‌هایی درباره‌ی مهندسی فرانت‌اند مدرن، از HTML و CSS تا جاوااسکریپت و ابزارهایی که رابط‌ها را سریع و کاربرپسند نگه می‌دارند.', 'short_description' => 'HTML، CSS، جاوااسکریپت و ابزارهای ساخت رابط‌های سریع.'], ['name' => 'ری‌اکت و نکست', 'slug' => 'react-nextjs-fa', 'description' => 'نگاه عمیق به ری‌اکت، نکست و اکوسیستم اطراف آن‌ها؛ کامپوننت‌ها، رندرینگ و الگوهای کاربردی.', 'short_description' => 'ری‌اکت، نکست و اکوسیستم اطراف آن‌ها.'], ['name' => 'توسعه بک‌اند', 'slug' => 'backend-fa', 'description' => 'کد سمت سرور، APIها، پایگاه‌داده و تصمیم‌هایی که پشت یک بک‌اند قابل اتکا گرفته می‌شود.', 'short_description' => 'APIها، پایگاه‌داده و کد سمت سرور قابل اتکا.'], @@ -94,6 +96,9 @@ class RealBlogContentSeeder extends Seeder ['name' => 'Freelancing', 'slug' => 'freelancing'], ['name' => 'Web Design', 'slug' => 'design'], + ['name' => 'Database', 'slug' => 'database'], + ['name' => 'Git', 'slug' => 'git'], + ['name' => 'Testing', 'slug' => 'testing'], ['name' => 'ری‌اکت', 'slug' => 'react-fa'], ['name' => 'نکست', 'slug' => 'nextjs-fa'], ['name' => 'سئو', 'slug' => 'seo-fa'], @@ -107,6 +112,9 @@ class RealBlogContentSeeder extends Seeder ['name' => 'هوش مصنوعی', 'slug' => 'ai-fa'], ['name' => 'فریلنسری', 'slug' => 'freelancing-fa'], ['name' => 'طراحی وب', 'slug' => 'design-fa'], + ['name' => 'پایگاه داده', 'slug' => 'database-fa'], + ['name' => 'گیت', 'slug' => 'git-fa'], + ['name' => 'تست', 'slug' => 'testing-fa'], ]; $tagIds = []; @@ -158,6 +166,21 @@ Server-first is a great default, but "use client" at the right boundary is still ## The takeaway Think about the server/client boundary as a performance decision, not a fashion one. Rendering on the server by default, then pushing only what genuinely needs the browser, is a pattern that scales with your product. + +## Key takeaways +- Components render on the server by default, so keep use client a deliberate opt-in at the right boundary. +- Fetch data directly inside the component and let Next.js deduplicate and cache those requests. +- Measure the migration in bundle size and LCP; this blog's home page shed about 180 KB of JavaScript. +- Keep client components only for interactive forms, browser event listeners, and frequently changing context state. +- Treat the server and client split as a performance decision, not a passing fashion. + +## FAQ + +Q: Do I still need getServerSideProps or getStaticProps in the App Router? +A: No. In the App Router you fetch directly inside a component, and Next.js deduplicates and caches the requests for you. That removes a separate data-fetching step and a whole category of props-drilling bugs, and it keeps unnecessary JavaScript out of the page. + +Q: How do I decide whether a component should be a Client Component? +A: Ask where the work should run. Reserve use client for interactive forms with optimistic updates, components that listen to browser events such as scroll, and anything using context for frequently changing state. Everything else can stay on the server. TEXT, ], [ @@ -198,6 +221,21 @@ Run Lighthouse for a quick lab pass, then compare it to CrUX field data for your ## The takeaway Performance is not a one-time checklist. Set the targets, add the metrics to your CI, and treat every release that regresses them as a bug. + +## Key takeaways +- Judge performance with field data, because Core Web Vitals describe what real users experience, not lab results. +- Preload the hero image and its stylesheet, then move render-blocking third-party scripts out of the critical path. +- Keep main-thread long tasks under 50 milliseconds and debounce expensive handlers to protect the 200 millisecond INP limit. +- Reserve explicit space for images and embeds so nothing shifts and CLS stays below 0.1. +- Add the metrics to CI and treat any release that regresses them as a bug, not a follow-up ticket. + +## FAQ + +Q: Which is better for checking my work, Lighthouse or CrUX? +A: Use both, for different jobs. Lighthouse gives a quick lab pass you can run on every change, while CrUX field data shows what your real traffic experienced. Search engines ultimately judge field performance, so a tool that reports RUM metrics is worth the setup cost. + +Q: Why is my CLS worse than my LCP after a redesign? +A: Most layout shift comes from content arriving without reserved space. Give images and embeds explicit dimensions, avoid inserting anything above content that already exists, and let fonts keep their fallback metrics so text does not reflow when the real font arrives. TEXT, ], [ @@ -232,6 +270,21 @@ The blog and website APIs follow exactly this pattern: form requests for validat ## The takeaway Small, boring conventions beat clever abstractions. A consistent response shape, centralised validation and sensible throttling will take an API from "works for me" to "works for everyone". + +## Key takeaways +- Define the response shape once with API resources so clients never guess whether a payload is an object or an array. +- Move validation, authorisation and rules into Form Requests so they live together and can be tested in isolation. +- Return the default 422 error shape, since most clients already know how to parse it. +- Throttle every public write route, then tune the number from what legitimate clients actually need. +- Remember a public contact form needs far more protection than an authenticated admin route. + +## FAQ + +Q: Why move validation out of the controller into a Form Request? +A: Rules inside a controller work until they stop scaling. A Form Request keeps validation, authorisation and rules next to each other, lets you test them in isolation, and keeps the rules close to the domain they describe. + +Q: How do I choose a sensible rate limit for a public endpoint? +A: Start with something reasonable, such as a few attempts per minute, and watch what legitimate clients actually need before tuning it. A public contact form deserves more protection than an authenticated admin route, because anonymous traffic can flood the database. TEXT, ], [ @@ -266,6 +319,21 @@ The deploy script for this site pulls the new images, runs a migration guard, st ## The takeaway Zero downtime is a composition of small habits: a real health endpoint, a proxy that respects it, and a deploy script that will not celebrate early. Automate the checks and your teammates will thank you. + +## Key takeaways +- Put a reverse proxy in front of the stack and let it forward traffic only to containers reporting healthy. +- Make the health endpoint check the database connection, not just return a 200 status code. +- Run migrations as a separate one-shot service so they finish before the web container restarts. +- Give the first boot a generous health-check start period so slow starts are not killed. +- Verify a health URL returns 200 before the deploy script reports success, and watch the logs during the switch. + +## FAQ + +Q: What actually makes a Docker Compose update zero-downtime? +A: The combination of a reverse proxy and a real health check. Compose recreates changed containers one by one, so as long as the proxy forwards traffic only to healthy containers, the old container keeps serving while the new one boots. + +Q: What should a health endpoint check before I call a deploy successful? +A: More than a status code. The endpoint should verify the database connection behind it, and the deploy script should fetch a health URL and see 200 before it reports success. That verification step is what turns a deploy from a wish into a fact. TEXT, ], [ @@ -300,6 +368,21 @@ Reciting a list of hook names tells me a candidate can memorize; it tells me not ## The takeaway Interviews should simulate the job: trade-offs, debugging and clear communication. Questions that reward those skills find engineers who actually ship. + +## Key takeaways +- Drop trivia questions and measure judgement, debugging skill and the ability to explain trade-offs instead. +- Ask questions that mirror the job, from what happens between the URL and first paint to a failing npm ci. +- Reward candidates who name real browser steps over those who quote documentation back at you. +- Treat an honest it depends, followed by naming the dependence, as a strong signal. +- Value debugging confidence and visible reasoning more than a perfect first answer. + +## FAQ + +Q: Why stop asking questions like which hooks exist? +A: Reciting hook names only shows someone can memorise, and it says nothing about how they behave on Monday morning. The questions that matter measure judgement, debugging skill and the ability to explain trade-offs, which is what the job actually demands. + +Q: What does a strong answer look like when a candidate is stuck? +A: I want to hear how they think, not whether they guessed right. Naming the actual browser steps beats quoting docs, and a candidate who says it depends and then names the dependence is my favourite kind of engineer. TEXT, ], [ @@ -338,6 +421,21 @@ Pages and post bodies are server-rendered, while the theme toggle and the mobile ## The takeaway Stop thinking "this component can use hooks, therefore client". Ask where the work should run, then let the framework handle the rest. + +## Key takeaways +- Ask where the work should run: server components render where the data lives, client components where the user is. +- Keep interactive leaves as client components and push server components up toward the data roots. +- Remember props crossing the boundary become serialized data, so functions and class instances never survive it. +- Split a component that is both into a client wrapper and a server body instead of guessing at the boundary. +- Give display-only sections to the server so you ship zero runtime JavaScript for them. + +## FAQ + +Q: What makes a component a Client Component? +A: Not the ability to use hooks, but the work it needs to do. State, effects, event handlers, browser APIs like geometry, media queries and storage, and interactivity users feel immediately are what force a component to be client. + +Q: What breaks when I pass props from a Server Component to a Client Component? +A: Props crossing that boundary become serialized data, and functions and class instances do not survive it, so surprises hide there. Keep client components near the interaction leaves and push server components up toward the data roots. TEXT, ], @@ -407,6 +505,21 @@ My default: host in Iran if your audience is entirely domestic, or in a nearby r - Compare before and after with real-user monitoring segmented by country. Core Web Vitals are not mysterious, and for a Persian site they are rarely about cleverness. They are about removing weight, choosing fewer font weights, and measuring from where your users actually are. + +## Key takeaways +- Load one Persian font family, two weights maximum, subset and preloaded. It is the highest-leverage fix available. +- Never lazy-load the LCP candidate. Compress it, serve AVIF with a WebP fallback, and declare explicit width and height. +- Verify line-height and layout with real Persian strings, including ZWNJ and Persian digits, not English placeholders. +- Judge hosting and CDN choices from real-user data inside Iran, because a site can be excellent in Frankfurt and mediocre in Tehran. +- Prioritize being fast, crawlable and indexable first, then add structured data only where it is genuinely accurate. + +## FAQ + +Q: My Persian site ranks fine but traffic is flat. Where do I start? +A: The same three numbers fail almost every time: LCP, INP and CLS. The causes are a heavyweight theme stacked with plugins, Persian webfonts loaded as multiple weights, and untouched hero images. + +Q: Should I use font-display swap or optional? +A: swap renders fallback Latin metrics first, then reflows Persian text, which directly causes CLS. optional avoids that reflow but a cold-cache visitor may see the fallback, so I test optional with a tight preload and let field CLS decide. TEXT, ], [ @@ -481,6 +594,21 @@ For juniors I advise taking two or three domestic projects to build a portfolio, Rates plateau early unless you move toward higher-leverage work: architecture, performance, data, security, or part ownership of a product. Every year, either your scope gets wider or your number gets smaller. The developers doing well did not work the most hours. They made one thing public, wrote about it honestly, and let that compound while they started the next thing. + +## Key takeaways +- Sell outcomes with numbers attached. An hourly rate puts you at the bottom of the global supply of developers. +- Build three proof assets in order: a deployed project people can click, a technical blog, and a clean GitHub. +- Quote anything outside the agreed deliverable separately. That habit roughly doubled my effective rate without a price rise. +- Never start without a written scope and a deposit, and solve the payment route before you sign anything. +- Write technical English well. For foreign teams documentation is part of the job, not an interruption. + +## FAQ + +Q: What to fix first when starting to freelance from Iran? +A: Position on outcomes rather than hours, then build a portfolio that works while you sleep: a deployed project, a technical blog, a clean GitHub. + +Q: Is cryptocurrency a safe way to get paid? +A: It has become the default settlement path many Iranian freelancers use because it avoids banking friction, and I use it without romanticizing it. It also carries volatility, counterparty risk and regulatory ambiguity, so convert earnings into something stable. TEXT, ], [ @@ -555,6 +683,21 @@ AI makes the first eighty percent of many tasks much cheaper and faster, and sha If you are in Iran and worried, do not compete with the model on volume. Become the engineer whose judgment is hard to fake and whose work is easy for anyone to evaluate. I have never seen a shortage of clients for that person. I have seen a shortage of them everywhere. + +## Key takeaways +- Treat reviewing generated code as the core competency. Prompting is table stakes, verification is the job. +- Move toward work where AI output needs human judgment: product sense, debugging, performance, security, architecture. +- Learn infrastructure, Linux, Docker, CI, databases and observability. That is what separates a senior from a fast junior. +- Write in English. Technical writing is both a learning mechanism and my best source of inbound leads. +- Do not compete with the model on volume. Own the whole slice from problem to deploy to measurement. + +## FAQ + +Q: Will AI take my programming job? +A: The floor of this market is falling fast while the ceiling is not moving, because routine implementation work is priced lower every quarter. Jobs do not vanish, but fewer people maintain hand-written code and more own outcomes. + +Q: Where should a junior in Iran start? +A: Not with a framework, shipping nothing and waiting for a job, because frameworks were always the part that got automated. Spend your first year on fundamentals, ship small real things immediately, and use AI as a pair after attempting it yourself. TEXT, ], [ @@ -616,6 +759,21 @@ A marketplace template theme runs a few million Toman, and you will spend more f ## The point A small business site does not need to impress designers. It needs to load in a few seconds on a cheap phone, say exactly what the business sells and how to reach it, and look like a real business with a real address. Everything else is decoration. + +## Key takeaways +- Design mobile first and right to left, because most traffic arrives from an Instagram bio or a Telegram channel. +- Cut the hero carousel, the extra font families, and every plugin whose only job is animation. +- Trust is what converts: real address, map, business licence, enamad badge, an answered phone, real reviews. +- Sell through a catalog grid with a WhatsApp button, not a full checkout platform, because buyers finish inside the app they use. +- Target LCP under 2.5 seconds, ideally under 1.8, on a throttled Iranian mobile connection. + +## FAQ + +Q: What does a small business website in Iran actually need? +A: It must load in a few seconds on a cheap phone, say what the business sells and how to reach it, and look like a real business with a real address. Impressing designers is not the goal. + +Q: Should I build a cart or a booking flow? +A: Most need a catalog, not a checkout platform: one photo, a price, and a WhatsApp button with a pre-filled message. That converts better because the buyer finishes the order inside the app they already use. TEXT, ], [ @@ -674,6 +832,21 @@ Then there is remote work for Iranian contractors, where the real spread appears Do not name your current salary first. Ask for the approved range. Remember that Iranian employees contribute to social insurance through payroll, which is a meaningful part of the package compared with invoicing as a freelancer, where you cover the full amount yourself. Ask about bonuses, working hours, leave, and whether they pay for your tools or training. With foreign clients, get the currency, rate and payment terms in writing before you start, and always take a deposit. Choose employment when you still need to learn fast. Choose freelance when you already have the skill and the network. The market will not decide this for you. + +## Key takeaways +- React is still the default for product work in Iran, but the bar moved up sharply for juniors without fundamentals. +- Learn the full width of the stack: data layer, real tests, performance and observability, plus enough backend to debug at 2am. +- Match the income model to your stage: employment early, hybrid in mid-career, freelance only with about six months of runway. +- Build two or three deep case studies, each ending in one number. Numbers land harder than screenshots. +- Never name your current salary first. Ask for the approved range, and price in the social insurance you contribute. + +## FAQ + +Q: React job or freelance in Iran? +A: It depends on your level and runway, not the framework. Under two years of experience, take employment because you need code review and mentorship. A senior with six months of runway can beat a salary, but only with a written contract. + +Q: Is remote work abroad realistic from Iran? +A: It pays multiples more in hard currency, and plenty of engineers manage it, but it is not a default plan. The obstacles are concrete: sanctions, payment and account access, overlapping European hours, and interviews in English. TEXT, ], [ @@ -734,10 +907,491 @@ Do not reach for the Google Fonts loader. Google Fonts is filtered on most Irani ## What success looks like Compare before and after on identical pages. On the sites I have moved, LCP typically drops from four or five seconds to under two, and INP improves even more because the page builder is gone. Traffic should be flat within a few weeks once redirects settle, and often grows because of the speed. Migrate one template at a time. + +## Key takeaways +- Baseline before touching anything: export every indexed URL, a year of Search Console data, and LCP, INP and CLS per template. +- Page builders are what kill LCP and INP here, not images or hosting. Removing the builder does most of the work. +- Map every old URL and keep the path structure identical. Redirect to the closest equivalent, never to the homepage. +- Keep Persian and Arabic slugs unchanged and un-normalised, because normalising them breaks links and search equity. +- Use static generation by default, and add incremental revalidation only where content changes daily. + +## FAQ + +Q: Is migrating to Next.js worth it? +A: When Core Web Vitals are bad because of the theme and page builder rather than the content, and the owner wants speed without losing years of URLs and backlinks. LCP typically drops from four or five seconds to under two. + +Q: Should I keep WordPress as a CMS? +A: Keep it headless and fetch content at build or request time, or import everything into markdown, MDX or a headless CMS and generate static pages. Most clients end up with static content plus a small editor. TEXT, ], // ================================================================= + [ + 'title' => 'Clean Architecture in Laravel Without the Acronym Sprawl: A Folder Layout That Survives Real Projects', + 'slug' => 'clean-architecture-laravel', + 'excerpt' => 'A pragmatic folder split for Laravel that keeps Eloquent at the boundary, respects dependency direction, and avoids over-engineering small CRUD apps.', + 'category' => 'backend-development', + 'tags' => ['laravel', 'clean-code'], + 'cover' => 'Clean architecture in Laravel', + 'views' => 1940, + 'likes' => 136, + 'days_ago' => 8, + 'body' => <<<'TEXT' +# Clean Architecture in Laravel Without the Acronym Sprawl: A Folder Layout That Survives Real Projects + +Clean architecture is often taught with a wall of acronyms: entities, use cases, interfaces, adapters, ports. That is useful in theory, but in real Laravel projects it usually leads to over-engineering. The goal is not to tick boxes. The goal is to keep business logic independent from framework details so the codebase survives years of change. + +## The pragmatic split + +A simple, battle-tested approach is to split code into three core layers: Domain, Application, and Infrastructure. This keeps the dependency direction clear without inventing twenty namespaces. + +Domain contains the core business concepts. This includes entities, value objects, enums, and domain rules. Nothing in Domain should depend on Laravel, Eloquent, HTTP, or external APIs. It should be pure PHP that represents your business. + +Application contains the use cases: what the system does. This is where you coordinate workflows, apply business rules, and define interfaces for external dependencies. Application depends only on Domain. It does not know about controllers, jobs, or databases. + +Infrastructure is the outermost layer. This is where Laravel lives: Eloquent models, repositories, jobs, HTTP clients, services that call third parties, and framework-specific code. Infrastructure implements the interfaces defined in Application and depends on both Application and Domain. + +## Keeping Eloquent in the repository boundary + +One of the most common mistakes is letting Eloquent leak everywhere. Eloquent models are convenient, but they couple your business logic to the database schema and framework features. The pragmatic fix is to treat Eloquent as an implementation detail. + +Define repository interfaces in the Application layer. For example, an OrderRepository interface that describes methods like findById or save. Implement that interface in Infrastructure using Eloquent models. Your use cases depend only on the interface, not on the model classes. This makes it easy to swap implementations or test use cases with in-memory fakes. + +Also, avoid returning Eloquent collections or models from repositories to the Application layer. Map them to Domain entities or simple DTOs. This keeps the boundary clean and prevents lazy loading or framework behavior from creeping into your business logic. + +## Dependency direction matters + +The key rule is: dependencies point inward. Infrastructure can depend on Application and Domain. Application can depend only on Domain. Domain depends on nothing outside itself. This is the core of keeping your code decoupled from the framework. + +Controllers, routes, jobs, and commands live in Infrastructure. They should be thin orchestrators. They call Application use cases, map HTTP requests to DTOs, and return responses. If your controllers are doing validation, calculations, or complex queries, that logic probably belongs in Application or Domain. + +## When not to over-layer + +Clean architecture has a cost. For a small CRUD app, adding three layers for every feature creates unnecessary indirection. If your app is mostly data entry with little business logic, a traditional Laravel structure is perfectly fine. + +The signal to add layers is complexity. If you have non-trivial business rules, multiple integrations, or the domain is likely to outlive the framework choice, the investment pays off. If you are still validating product-market fit, keep it simple and refactor toward these boundaries as complexity emerges. + +## Practical folder layout + +A minimal, maintainable structure looks like this. In app/, create Domain/, Application/, and Infrastructure/. Alternatively, use src/ if you prefer. Keep Laravel's existing directories where they make sense, but move business logic out. + +Domain can hold Entities/, ValueObjects/, Enums/, and domain-specific exceptions. Application can hold UseCases/, Contracts/ (interfaces), DTOs/, and Policies/. Infrastructure can hold Repositories/, Services/, Jobs/, Http/Controllers/, and any framework-specific adapters. + +This keeps namespaces clear and makes it obvious where new code belongs. New developers can follow the dependency rule without memorizing every acronym from the textbooks. + +## Key takeaways + +- Split into Domain, Application, Infrastructure to keep business logic framework-agnostic. +- Define repository interfaces in Application and implement them with Eloquent in Infrastructure. +- Map Eloquent models to Domain entities or DTOs at the boundary, never leak models inward. +- Follow the inward dependency rule: Infrastructure depends outward, Domain depends on nothing. +- Only layer when business complexity justifies it. Small CRUD apps do not need full clean architecture. + +## FAQ + +Q: Do I have to throw away Eloquent? +A: No. Eloquent is a great ORM. Keep it in Infrastructure as an implementation detail behind repository interfaces. + +Q: Is this the same as hexagonal architecture? +A: Similar idea, different naming. The goal is ports and adapters: isolate the core from external concerns. This pragmatic split captures that without acronym sprawl. + +Q: How do I test this structure? +A: Test Domain and Application with fast unit tests (no Laravel). Test Infrastructure with integration tests that use the database or mocks as needed. This keeps your feedback loop fast. +TEXT, + ], + + [ + 'title' => 'A Git Branching and Code Review Workflow That Scales Past Five Developers', + 'slug' => 'git-branching-and-reviews', + 'excerpt' => 'Branching strategy is not the bottleneck, review quality is. Short-lived branches, atomic commits, protected main and automated checks take a five person team to twenty without the arguments.', + 'category' => 'engineering-practices', + 'tags' => ['git', 'clean-code'], + 'cover' => 'Git workflow and code reviews', + 'views' => 2340, + 'likes' => 155, + 'days_ago' => 17, + 'body' => <<<'TEXT' +# A Git Branching and Code Review Workflow That Scales Past Five Developers + +Most teams blame branching strategy when they hit a wall around six developers. The thing that actually degrades with headcount is the quality and the latency of code review. Here is the workflow I install on every project, and the reason behind each piece. + +## Short-lived branches beat long-lived ones + +A branch that lives three weeks carries three weeks of changes you have not seen and ends in a painful merge. It exists so you can work in parallel, then hand something reviewable to the next person. + +- Open the branch the day you start and merge it within a day. +- If it will not merge quickly, the change is too big. Split it. +- Long-lived experiment branches only work if that code never ships in between. +- Delete branches on merge, or nobody can tell which work is real. + +## Trunk based versus feature branches, in practice + +They are not opposites. Trunk based means main is always releasable, and short branches are perfectly fine inside that. You branch from main for a few hours, open a pull request, merge after review. Avoid the other extreme, where every developer keeps a personal branch for months. That model works until two people touch the same migration. + +## Commits that are atomic and reviewable + +A commit is a unit of meaning, not a unit of time. One thing, tests passing on their own, revertable on their own. That property is what gives you bisect and clean reverts. + +- Separate a refactor from a behaviour change. +- Write the message for whoever runs bisect six months from now. +- Why it changed matters more than what the diff already shows. +- Keep history short. Ten commits of a day's work is fine. + +## What a good review actually checks + +Review exists for correctness and shared understanding, not formatting. A formatter in CI already owns indentation, import order and line length. Reviewers who spend their attention there leave the real problems untouched. + +- Does it do what the ticket says, including the unwritten parts, and nothing else? +- What happens on empty input, very large input and concurrent requests? +- Do the tests cover behaviour, or do they just restate the implementation? +- Is anything sensitive in the diff, a token, a personal identifier, an unbounded query? +- Will a newcomer understand this in six months? + +Comments should say what and why, never only what. A review full of restated lines is noise, and noisy reviews get skimmed. + +## Protecting main and automating the boring checks + +The cheapest way to speed up review is to remove the questions a reviewer should never have to ask. Anything mechanical belongs in CI, because a human should not spend a review cycle on a missing newline. + +- Require a pull request for main with at least one approval. +- Block direct pushes to main. +- Make format, lint, typecheck and tests required status checks. +- Keep the pipeline under ten minutes and parallelize as it grows. +- Merge with squash or rebase so main stays linear. + +## Key takeaways + +- Branch for hours, not weeks, because review cost scales with diff size. +- Keep main always releasable and merge small branches into it daily. +- Write atomic commits with messages aimed at a future bisect. +- Review behaviour and risk, and let the formatter own style. +- Automate every mechanical check so reviewer attention goes to correctness. + +## FAQ + +Q: Is trunk based development workable for a team that releases monthly? + +A: Yes, and it fits monthly releases better than long-lived branches do. You merge to main daily and control what goes live with tags or feature flags, so main stays releasable while the release happens on your schedule. A monthly cycle is a release concern, not a branching concern. + +Q: Our reviews are slow, should we require two approvals? + +A: Not first. Slow reviews usually mean the diff is too large, the ticket is unclear or the author asked too late. Fix those and make sure mechanical checks run in CI so reviewers are not acting as linters. Only then is tightening rules for migrations and auth code sensible. +TEXT, + ], + + [ + 'title' => 'SQL Indexes That Make Queries Fast: A Practical Guide With Laravel', + 'slug' => 'sql-indexes-database-performance', + 'excerpt' => 'A slow Laravel endpoint is almost never a slow server. Here is how to read EXPLAIN, order composite index columns correctly, add covering indexes and index foreign keys without slowing your writes down.', + 'category' => 'backend-development', + 'tags' => ['database', 'performance'], + 'cover' => 'SQL indexes for fast queries', + 'views' => 1960, + 'likes' => 128, + 'days_ago' => 9, + 'body' => <<<'TEXT' +# SQL Indexes That Make Queries Fast: A Practical Guide With Laravel + +Almost every slow endpoint I get asked about has the same cause, a table scan on a column with no index. Laravel makes that easy to write and easy to forget, because nobody notices until the table passes a hundred thousand rows. + +## What an index actually does + +MySQL and PostgreSQL store indexes in a B-tree, whose keys stay sorted and whose leaves sit next to each other in storage. That one property explains the behaviour: finding a single key touches a few pages instead of every row, and two conditions on one column are served by walking the tree once from the start of the range to its end. + +The other half matters too: every insert and update must be written into every index, so an index is a tax you pay on writes to buy fast reads. + +## Reading EXPLAIN without guessing + +Run EXPLAIN on the real query with real parameters and read it top to bottom, looking at the access type, the estimated rows, the filtered percentage and the extra column. + +- A sequential scan on a large table means no usable index. Check the column and the value type. +- An index scan with a huge row estimate means the index is not selective enough for the optimizer. +- Rows removed by a filter usually means a wildcard or a non-sargable expression. +- A temporary table or filesort means ORDER BY could not be served from index order, so fix the index first. +- A dependent subquery often points at an N plus one in Eloquent, one query per parent row. + +## Composite index column order + +A multi-column index is not several indexes, it is one sorted list, and the column order decides which queries it serves: equality conditions first, then one range column, then columns used only for sorting or covering. + +- Filtering on a tenant column and a created_at range uses an index on both, because the range stops at the first ranged column. +- Filtering on a user column and sorting by created_at descending also works, since the engine walks the index backwards. +- Prepending an equality column often makes the old single-column index redundant. +- Test the direction you query, because mixing ascending and descending changes what the engine can do. + +## Covering indexes + +A covering index holds every column the query needs, so the database answers from the index and never visits the table. Add those columns to an existing index rather than creating another, and look for the word covering in the EXPLAIN extra column. The catch is write amplification, so this belongs on your few hot queries. + +## Foreign keys and the cost of over-indexing + +Foreign key columns need indexes for a reason unrelated to convenience: when a row is deleted, the engine must prove no child rows point at it, and without an index that check becomes a table scan while holding locks. + +- Index every foreign key column and every join column, this is the cheapest win in the system. +- Index the columns you filter, sort and join, but not columns you only select. +- In Laravel put indexes in migrations, not in a manual console session. +- Log every query in tests, which catches N plus one regressions before production. + +## Key takeaways + +- An index is a B-tree, so sorting and range scans get cheap while every write pays. +- Read access type, row estimate and extra in EXPLAIN before touching code. +- Equality columns first, then one range column, then sorting columns. +- Covering indexes answer without touching the table, so keep them on hot paths. +- Index every foreign key and keep the total small enough that writes stay fast. + +## FAQ + +Q: How do I find out which indexes are actually used in production? + +A: Enable the performance schema or your provider slow query log, then compare the important queries with your index definitions. In MySQL it gives a per-table counter for unused indexes, and dropping them after a representative traffic window is the safest way to remove an index that only slows writes. + +Q: Is it bad to index every column that appears in a WHERE clause? + +A: It becomes bad as soon as write volume matters, because every index is updated on each insert and update. Ask instead which queries are frequent or slow, since a single well-ordered composite index usually serves several conditions at once. +TEXT, + ], + + [ + 'title' => 'TypeScript Beyond the Basics: Generics, Utility Types and Strict Mode in Real Projects', + 'slug' => 'typescript-advanced-patterns', + 'excerpt' => 'Most teams use TypeScript as a linter and stop there. Generics that preserve your domain types, a short set of utility types, and the two compiler flags people skip are what turn the compiler into a refactoring tool.', + 'category' => 'frontend-development', + 'tags' => ['typescript', 'clean-code'], + 'cover' => 'TypeScript patterns for real projects', + 'views' => 2180, + 'likes' => 142, + 'days_ago' => 4, + 'body' => <<<'TEXT' +# TypeScript Beyond the Basics: Generics, Utility Types and Strict Mode in Real Projects + +Most teams adopt TypeScript for autocomplete and to stop shipping the classic string versus number mistakes. Six months later the codebase is full of any casts and a compiler config nobody dares to touch. That gap is vocabulary, not effort. + +## Generics that earn their keep + +A generic earns its place when one piece of logic must serve several shapes without any of them losing type information. If you end the implementation with a cast, you needed a plain function. + +- A repository that takes the entity type once and returns it from every method. +- A form builder where each field declares its value type and the result is inferred. +- A table component taking a row type plus accessors, so sorting stays correct per column. +- A typed event emitter whose map defines payloads and legal event names. + +Two constraints do the heavy lifting, since keyof T accepts only keys the type really has and extends string keeps an argument inside a known family. + +## The utility types you actually need + +Nobody memorises a hundred of these. A short set covers almost everything, and composing them in one named alias beats inventing a type per model. + +- Partial for update payloads and form models. +- Pick and Omit to build request DTOs without repeating a field name. +- ReturnType and Parameters so a hook documents its own shape once. +- NonNullable for values that come back from a nullable column. +- Record for a typed dictionary instead of a permissive index signature. +- Awaited to unwrap promises returned by clients that return promises. + +## The two compiler flags people skip + +Strict mode is the baseline. The upgrade almost nobody enables is noUncheckedIndexedAccess, and it catches the most real bugs, because reading outside a known range is the commonest source of runtime undefined. + +- Array and record access becomes value or undefined, so out-of-range reads fail to compile. +- Strict null checks force you to handle the missing case instead of asserting it away. +- exactOptionalPropertyTypes blocks assigning undefined to an optional field. +- noImplicitOverride and the switch fallthrough flag clean up inheritance mistakes. + +Turning them on for an old codebase produces a burst of errors, so enable them for new modules and fix files as you touch them. + +## Discriminated unions beat optional fields + +An object with three booleans and four nullable fields has eight meaningful states and the compiler checks none of them. A union with a literal status makes the invalid combinations type errors. + +- Model a payment as created, captured or refunded, not a status string with nullable fields. +- Model a form flow as a union of step objects, each carrying only its own data. +- Narrow with a switch on the discriminant and the union narrows inside each branch. + +## Where to stop + +Type-level programming has a ceiling, and crossing it is the fastest way to make a team distrust its own types. + +- Do not build a type that needs a comment longer than the code it replaces. +- Do not hide one implementation behind a generic parameter until a second one exists. +- Do not encode business rules in types, encode states and relationships. +- Parse external data once at the boundary, then use that type everywhere else. + +## Key takeaways + +- Add a generic only when shapes share behaviour and stay distinguishable. +- Keep a short set of utility types and compose them. +- Turn on noUncheckedIndexedAccess first, then the other strict flags file by file. +- Replace clusters of nullable fields with discriminated unions. +- Stop before the types get harder to read than the logic. + +## FAQ + +Q: Does heavy type level code slow the compiler down on a large codebase? + +A: Sometimes, and the cost lands on the largest files, not the whole project. Deep mapped types and generics instantiated with large unions are the usual culprits, so simplify a couple of aliases rather than removing the flags. + +Q: Should I enable strict mode on an existing codebase at once? + +A: Not at once. Keep the flags out of the global build for legacy folders, apply them to new modules immediately, and fix errors in small batches as you touch each file. +TEXT, + ], + + [ + 'title' => 'What Actually Happens When the Browser Loads a Page: From DNS to a 90 Lighthouse Score', + 'slug' => 'how-the-browser-loads-a-page', + 'excerpt' => 'A practical breakdown of browser page loading with actionable steps to improve performance and Core Web Vitals for better SEO and UX.', + 'category' => 'web-performance-seo', + 'tags' => ['performance', 'seo'], + 'cover' => 'How a browser loads a page', + 'views' => 2150, + 'likes' => 138, + 'days_ago' => 15, + 'body' => <<<'TEXT' +# What Actually Happens When the Browser Loads a Page: From DNS to a 90 Lighthouse Score + +When a user types a URL and hits enter, a lot happens in milliseconds. Understanding this process is not just academic. It helps you debug slow sites, prioritize fixes, and improve both user experience and SEO. Here is what actually happens, step by step, and how each stage affects performance. + +## DNS lookup and initial connection + +The first step is resolving the domain name to an IP address. The browser checks its cache, the OS cache, the router, and finally DNS servers. Slow DNS adds unnecessary latency, especially on mobile networks. + +Once the IP is known, the browser establishes a TCP connection. For HTTPS sites, this includes TLS handshake to negotiate encryption. TLS 1.3 has reduced handshake round trips significantly compared to older versions. Connection reuse, through keep-alive or HTTP/2 multiplexing, prevents paying this cost for every resource. + +## HTTP requests and connection protocols + +Modern sites use HTTP/2 or HTTP/3. With HTTP/1.1, browsers limited concurrent requests per domain, leading to waterfall bottlenecks. HTTP/2 allows multiplexing multiple requests over one connection. HTTP/3 moves to QUIC over UDP, reducing head-of-line blocking and improving performance on unreliable networks. + +The browser first requests the HTML document. This is usually a small text file, but it is the key that unlocks everything else. How the server delivers it, compression (like gzip or Brotli), and caching headers all affect first load time. + +## HTML parsing and building the DOM + +As the browser receives HTML bytes, it parses them into tokens, then into the DOM tree. This is a streaming process; the browser can start parsing before the entire document is downloaded. However, parsing is blocked when it encounters synchronous scripts without defer or async. + +While parsing HTML, the browser discovers references to external resources: stylesheets, scripts, images, fonts, and more. Each discovery triggers a new request, which can either be queued or started depending on the protocol and priority. + +## Critical CSS and render-blocking resources + +CSS is render-blocking by default. The browser cannot render content until it has the CSSOM (CSS Object Model) constructed. Large, unoptimized stylesheets delay the first paint. A common optimization is to extract and inline critical CSS for above-the-fold content, then load the rest asynchronously. + +JavaScript is even more impactful. Synchronous scripts block HTML parsing and can delay rendering. Using script type=module, defer, or async changes when execution happens. defer preserves execution order and runs after DOM parsing. async runs as soon as it is downloaded, without preserving order. Moving non-critical scripts to the end or deferring them is key to improving perceived performance. + +## Preloading, prefetching, and resource hints + +Not all resources are discovered at the same time. The browser builds a preload scanner that looks ahead in the HTML to discover resources earlier. You can also give explicit hints: link rel=preload for critical resources like fonts or hero images, preconnect to establish connections early, and prefetch for resources likely needed on the next page. + +These hints help the browser prioritize what matters most for the current view. Used correctly, they reduce load delays without overloading the network. + +## Images, fonts, and layout stability + +Images often account for the largest bytes. Optimizations like modern formats (WebP, AVIF), responsive srcset, lazy loading offscreen images, and proper sizing reduce both bytes and layout shifts. Decoding large images can also block the main thread; using decoding=async or proper sizing helps. + +Fonts can cause invisible text or layout shifts if not handled well. font-display: swap shows fallback text quickly while the web font loads, improving perceived performance. Preloading critical fonts reduces the chance of FOIT (Flash of Invisible Text). + +Cumulative Layout Shift (CLS) comes from content shifting after initial render. Reserving space for images, ads, or dynamic content is one of the most effective ways to improve CLS. + +## The rendering pipeline and Core Web Vitals + +Once CSSOM and DOM are ready, the browser constructs the render tree, computes layout, paints pixels, and composites layers. This happens frame by frame. Long tasks on the main thread block interactivity. + +Core Web Vitals map directly to this pipeline. Largest Contentful Paint (LCP) measures when the largest visible element loads, often a hero image or heading. Interaction to Next Paint (INP) measures responsiveness to user input. Cumulative Layout Shift (CLS) measures visual stability. These metrics heavily influence Lighthouse scores and SEO rankings. + +## Getting to a 90 Lighthouse score + +Reaching 90+ is achievable by focusing on high-impact fixes. Optimize images and serve them in modern formats. Defer or lazy-load non-critical JavaScript. Inline critical CSS and eliminate render-blocking resources. Use caching headers and a CDN to reduce Time to First Byte (TTFB). Preconnect to third-party domains and preload critical assets. Finally, minimize layout shifts by reserving space for dynamic elements. + +The key is not doing everything. It is fixing what blocks the critical path for your specific page. Profile with Chrome DevTools and Lighthouse, measure, then iterate. + +## Key takeaways + +- DNS, TCP, and TLS add connection latency; reuse connections and use HTTP/2 or HTTP/3. +- HTML parsing is streaming but blocked by synchronous scripts; use defer/async for non-critical JS. +- CSS blocks rendering; inline critical CSS and load the rest efficiently. +- Preload critical assets and preconnect to important origins to reduce wait time. +- Optimize images, fonts, and layout to improve LCP, INP, and CLS for better Lighthouse scores. + +## FAQ + +Q: What is the single biggest factor for LCP? +A: Usually the hero image or large visible element. Optimizing its size, format, and load priority has the most impact. + +Q: Should I use async or defer for scripts? +A: Use defer for scripts that depend on DOM order. Use async for independent scripts like analytics that do not interact with page structure immediately. + +Q: How does HTTP/3 help performance? +A: HTTP/3 uses QUIC over UDP, reducing head-of-line blocking and recovering faster from packet loss, especially on mobile or unreliable networks. +TEXT, + ], + + [ + 'title' => 'Test-Driven Development When It Actually Pays Off: Writing Testable Code Without the Dogma', + 'slug' => 'tdd-writing-testable-code', + 'excerpt' => 'Learn when TDD speeds you up versus when it slows you down, and how the three-layer rule keeps tests fast and useful in real projects.', + 'category' => 'engineering-practices', + 'tags' => ['testing', 'clean-code'], + 'cover' => 'TDD and testable code', + 'views' => 1480, + 'likes' => 112, + 'days_ago' => 12, + 'body' => <<<'TEXT' +# Test-Driven Development When It Actually Pays Off: Writing Testable Code Without the Dogma + +The TDD debates tend to swing between two extremes. On one end, people treat it as a religious practice. On the other end, people dismiss it as unnecessary overhead. The truth is much more practical: TDD pays off in some domains, adds ceremony in others, and the value is not writing tests first. The value is being forced to write testable code from the start. + +## When TDD actually helps + +The biggest return comes from code that is likely to change or break. Business rules are a good example. Pricing calculations, tax logic, discounts, or validation rules tend to have many edge cases. Writing a failing test first makes those rules explicit and prevents regressions when requirements evolve. + +Parsing and transformation work also benefits. When you convert between formats, extract data, or normalize inputs, TDD lets you build up complex cases incrementally. Each test locks in behavior and gives you confidence to refactor without fear. + +Refactoring legacy code is another area where TDD shines. If you can put a small safety net of fast tests around a module first, you can restructure it safely. Finally, anything with high regression risk, like authentication, authorization, or financial calculations, is worth the upfront investment. + +## When it adds unnecessary ceremony + +Not all code deserves the red-green-refactor cycle. Throwaway UI prototypes, quick scripts for one-time data migration, or experiments you might throw away in a day rarely justify writing tests first. The same goes for purely presentational components where behavior is trivial and changes constantly based on feedback. + +The cost is not just writing tests. It is the context switching and the time spent maintaining tests that no longer reflect useful behavior. In those cases, it is better to write tests after stabilizing the behavior, or skip them entirely until the design solidifies. + +## The three-layer rule for testability + +The simplest way to write testable code without dogma is to separate concerns into three layers. The logic layer contains pure business rules with no side effects. This is where TDD is cheapest and most powerful because tests run instantly and have no dependencies. + +The effects layer handles I/O: database access, API calls, file system, queues, and external services. These are slower and often require mocks or test doubles. Keep this layer thin and push complexity to the logic layer. + +The interface layer is what talks to the outside world, like controllers, CLI commands, or UI handlers. This layer should orchestrate calls and map data. If most of your complexity lives in logic, your interface tests stay small and your integration tests stay focused. + +## Naming and assertion quality + +Tests are documentation for future developers. Good test names describe behavior, not implementation. Instead of testingFunctionReturnsTrue, say something like shouldApplyDiscountWhenSubtotalExceedsThreshold. This makes failures readable and intent clear. + +Assertions matter just as much. Prefer clear, specific assertions over generic ones. Avoid asserting on implementation details like private methods or internal object structure. Test observable behavior: inputs, outputs, side effects that matter, or state changes visible through the public API. This keeps tests resilient to refactors. + +## Keep tests fast so they run on every commit + +Speed is the single most important property of a useful test suite. If tests take minutes, they will only run in CI. If they take seconds, they will run before every commit. That is the difference between catching bugs early and discovering them hours later. + +To keep them fast, avoid hitting real databases, networks, or file systems in unit tests. Use fakes, stubs, or in-memory implementations. Reserve slow tests for critical integration paths and mark them separately. A fast feedback loop is what makes TDD feel like it speeds you up instead of slowing you down. + +## Key takeaways + +- Use TDD where behavior is stable enough to matter: business rules, parsing, refactors, and high regression areas. +- Skip or defer TDD for throwaway UI, prototypes, or rapidly changing experiments. +- Apply the three-layer rule: logic, effects, and interface to isolate complexity. +- Write behavior-focused test names and assert on observable outcomes, not internals. +- Prioritize speed so your test suite runs in every commit and keeps feedback tight. + +## FAQ + +Q: Should I always write tests first? +A: No. Write tests first when the requirements are clear enough to define expected behavior. If the design is still in flux, iterate on the implementation first and add tests once the shape stabilizes. + +Q: How much test coverage is enough? +A: Focus on covering critical paths and edge cases, not chasing 100 percent. High coverage of trivial code is low value. Good coverage of business-critical logic prevents the regressions that actually hurt users. + +Q: Do I need TDD to write testable code? +A: No. TDD is a discipline that tends to produce testable code, but you can also refactor toward testability. The goal is testable code with fast, meaningful tests, not strict adherence to the dogma. +TEXT, + ], // Persian posts // ================================================================= [ @@ -775,6 +1429,21 @@ TEXT, ## جمع‌بندی به مرز سرور و کلاینت به چشم یک تصمیم عملکردی نگاه کن، نه یک مد. رندر روی سرور به‌عنوان پیش‌فرض و ارسال فقط آنچه واقعاً به مرورگر نیاز دارد، الگویی است که با محصول هم رشد می‌کند. + +## نکات کلیدی +- کامپوننت‌ها به‌پیش‌فرض روی سرور رندر می‌شوند، پس use client را آگاهانه و فقط در مرز درست انتخاب کن. +- داده را مستقیم داخل خود کامپوننت بگیر و بگذار نکست درخواست‌ها را یکتا و کش کند. +- مهاجرت را با حجم باندل و LCP بسنج؛ صفحه‌ی اصلی این وبلاگ حدود ۱۸۰ کیلوبایت جاواسکریپت کم کرد. +- کلاینت کامپوننت را فقط برای فرم تعاملی، شنونده‌ی رویداد مرورگر و Context با تغییر مکرر نگه دار. +- مرز سرور و کلاینت را یک تصمیم عملکردی ببین، نه یک مُد گذرا. + +## FAQ + +Q: آیا در اپ روتر هنوز به getServerSideProps یا getStaticProps نیاز دارم؟ +A: نه. در اپ روتر مستقیم داخل کامپوننت داده می‌گیریم و خود نکست درخواست‌ها را یکتا و کش می‌کند. این کار هم قدم جداگانه‌ی بازیابی داده را حذف می‌کند و هم یک دسته کامل از باگ‌های سال‌ها‌نرم‌افزار را، و جاواسکریپت غیرضروری را از صفحه بیرون نگه می‌دارد. + +Q: از کجا بفهمم یک کامپوننت باید کلاینت کامپوننت باشد؟ +A: بپرس کار باید کجا اجرا شود. use client را برای فرم‌های تعاملی با به‌روزرسانی خوش‌بینانه، کامپوننت‌هایی که به رویدادهای مرورگر مثل اسکرول گوش می‌دهند و هر چیزی که از Context برای وضعیت مدام‌تغییرکننده استفاده می‌کند نگه دار. بقیه می‌تواند روی سرور بماند. TEXT, ], [ @@ -815,6 +1484,21 @@ CLS به صفحه‌هایی پاداش می‌دهد که هنگام بارگذ ## جمع‌بندی عملکرد یک چک‌لیست یک‌باره نیست. هدف‌ها را مشخص کن، سنجه‌ها را به CI اضافه کن و هر انتشار که آن‌ها را عقب می‌برد را یک باگ حساب کن. + +## نکات کلیدی +- سنجه‌ها را با داده‌ی میدانی قضاوت کن، چون وب وایتل‌ها تجربه‌ی واقعی کاربر را توصیف می‌کنند نه نتیجه‌ی تست آزمایشگاهی. +- تصویر قهرمان و استایل‌شیتِ مؤثر روی آن را پیش‌بارگذاری کن و اسکریپت‌های بلاک‌کننده را از مسیر بحرانی بیرون ببر. +- کارهای طولانی روی ترد اصلی را زیر ۵۰ میلی‌ثانیه نگه دار و هندلرهای گران را debounce کن. +- برای تصاویر و محتوای جاسازی‌شده فضای صریح رزرو کن تا چیدمان جابه‌جا نشود و CLS زیر ۰٫۱ بماند. +- سنجه‌ها را به CI اضافه کن و هر انتشاری که آن‌ها را عقب می‌برد را باگ حساب کن. + +## FAQ + +Q: برای بررسی کار، Lighthouse بهتر است یا CrUX؟ +A: هر دو، اما برای کارهای متفاوت. Lighthouse یک بررسی سریع آزمایشگاهی می‌دهد که روی هر تغییر قابل اجراست، درحالی‌که داده‌ی میدانی CrUX نشان می‌دهد ترافیک واقعی چه تجربه‌ای داشته. عملکرد میدانی همان چیزی است که موتور جست‌وجو نهایتاً می‌بیند. + +Q: چرا CLS من بعد از بازطراحی بدتر از LCP است؟ +A: بیشتر جابه‌جایی چیدمان از محتوایی می‌آید که بدون فضای رزروشده می‌رسد. برای تصاویر و محتوای جاسازی‌شده ابعاد صریح بده، چیزی بالای محتوای موجود درج نکن و بگذار فونت‌ها متریک‌های جایگزین‌شان را نگه دارند تا متن با رسیدن فونت اصلی جابه‌جا نشود. TEXT, ], [ @@ -846,6 +1530,21 @@ API وبلاگ و سایت دقیقاً همین الگو را دنبال می ## جمع‌بندی قراردادهای کوچک و خسته‌کننده از انتزاع‌های هوشمند بهترند. شکلِ پاسخِ یکدست، اعتبارسنجی متمرکز و throttle منطقی، API را از «روی من کار می‌کند» به «روی همه کار می‌کند» می‌رسانند. + +## نکات کلیدی +- شکل پاسخ را یک‌بار با API ریسورس تعریف کن تا کلاینت هیچ‌وقت حدس نزند آبجکت است یا آرایه. +- اعتبارسنجی، مجوزدهی و قوانین را به Form Request منتقل کن تا کنار هم بمانند و جدا قابل تست باشند. +- خطای پیش‌فرض ۴۲۲ را برگردان، چون بیشتر کلاینت‌ها از قبل آن را می‌فهمند. +- هر مسیر عمومیِ نوشتن را throttle کن و بعد عددش را با نیاز واقعی کلاینت‌ها تنظیم کن. +- فرم تماس عمومی به محافظت بیشتری از مسیر ادمینِ احراز هویت‌شده نیاز دارد. + +## FAQ + +Q: چرا اعتبارسنجی را از کنترلر به Form Request منتقل کنیم؟ +A: نوشتن قوانین داخل کنترلر تا جایی جواب می‌دهد که دیگر مقیاس نمی‌شود. Form Request اعتبارسنجی، مجوزدهی و قوانین را کنار هم نگه می‌دارد، اجازه می‌دهد جداگانه تستشان کنی و قوانین را نزدیک دامنه‌ی خودشان نگه می‌دارد. + +Q: چه محدودیت نرخی برای یک مسیر عمومی منطقی است؟ +A: با یک عدد منطقی شروع کن، مثلاً چند تلاش در دقیقه، و بعد از اینکه دیدی کلاینت‌های واقعی به چه چیزی نیاز دارند تنظیمش کن. فرم تماس عمومی به محافظت بیشتری از مسیر ادمینِ احراز هویت‌شده نیاز دارد، چون ترافیک ناشناس می‌تواند دیتابیس را غرق کند. TEXT, ], [ @@ -880,6 +1579,21 @@ TEXT, ## جمع‌بندی عدم توقف سرویس ترکیبی از عادت‌های کوچک است: اندپوینت سلامتِ واقعی، پراکسی‌ای که به آن احترام می‌گذارد و اسکریپتی که زود خوشحال نمی‌شود. بررسی‌ها را خودکار کن؛ همکارانت تشکر می‌کنند. + +## نکات کلیدی +- یک ریورس پراکسی جلوی استک بگذار و بگذار فقط به کانتینرهایی که healthy اعلام کرده‌اند ترافیک بدهد. +- اندپوینت سلامت را طوری بنویس که اتصال دیتابیس را بررسی کند، نه اینکه فقط ۲۰۰ برگرداند. +- مهاجرت‌ها را به‌صورت سرویس جداگانه‌ی one-shot اجرا کن تا قبل از ری‌استارت وب تمام شوند. +- برای بوت اول، start period سخاوتمندانه بگذار تا بوت‌های کند کشته نشوند. +- قبل از اعلام موفقیت، ۲۰۰ بودن URL سلامت را راستی‌آزمایی کن و هنگام جابه‌جایی لاگ‌ها را تماشا کن. + +## FAQ + +Q: چه چیزی یک به‌روزرسانی Docker Compose را بدون توقف می‌کند؟ +A: ترکیب ریورس پراکسی و یک health check واقعی. کامپوز کانتینرهای تغییرکرده را یکی‌یکی بازسازی می‌کند، پس تا وقتی پراکسی فقط به کانتینرهای healthy ترافیک بدهد، کانتینر قدیمی تا بوت شدن کانتینر جدید به درخواست‌ها پاسخ می‌دهد. + +Q: اندپوینت سلامت قبل از اعلام موفقیت استقرار باید چه چیزی را بررسی کند؟ +A: بیشتر از یک کد وضعیت. اندپوینت باید اتصال دیتابیس پشت آن را هم بررسی کند و اسکریپت استقرار باید قبل از اعلام موفقیت، URL سلامت را بگیرد و ۲۰۰ ببیند. همین قدم راستی‌آزمایی است که استقرار را از آرزو به واقعیت تبدیل می‌کند. TEXT, ], [ @@ -914,6 +1628,21 @@ TEXT, ## جمع‌بندی مصاحبه باید شغل را شبیه‌سازی کند: بده‌بستان، دیباگ و ارتباط شفاف. سؤال‌هایی که این‌ها را پاداش می‌دهند، آن مهندسانی را پیدا می‌کنند که واقعاً تحویل می‌دهند. + +## نکات کلیدی +- سؤال‌های حفظی را کنار بگذار و به‌جایش قضاوت، مهارت دیباگ و توان توضیح بده‌بستان‌ها را بسنج. +- سؤال‌هایی بپرس که شبیه شغل واقعی‌اند، از اتفاقات بین URL تا اولین پنت تا خرابی npm ci. +- کسی را ترجیح بده که مراحل واقعی مرورگر را نام ببرد، نه اینکه از مستندات نقل‌قول کند. +- «بسته به شرایط» گفتن و بعد نام بردنِ همان شرایط را نشانه‌ی قوی بدان. +- اعتمادبه‌نفس در دیباگ و روشن بودن مسیر فکر را از یک جواب اولِ بی‌نقص مهم‌تر بدان. + +## FAQ + +Q: چرا دیگر سؤال‌هایی مثل «کدام هوک‌ها وجود دارند» نمی‌پرسم؟ +A: حفظ کردن اسم هوک‌ها فقط نشان می‌دهد کسی بلد است حفظ کند، نه اینکه روز اول کارش چطور خواهد بود. سؤال‌های مهم قضاوت، مهارت دیباگ و توان توضیح بده‌بستان‌ها را می‌سنجند، چون کار واقعاً همین‌ها را می‌خواهد. + +Q: وقتی داوطلب گیر می‌کند، جواب قوی چه شکلی است؟ +A: می‌خواهم فرایند فکرش را بشنوم، نه اینکه حدسش درست بوده یا نه. نام بردن از مراحل واقعی مرورگر بهتر از نقل‌قول مستندات است، و «بسته به شرایط» گفتن و بعد نام بردن همان شرایط، مطلوب‌ترین جواب از نظر من است. TEXT, ], [ @@ -952,6 +1681,21 @@ TEXT, ## جمع‌بندی به‌جای «این کامپوننت هوک دارد پس کلاینت» بپرس کار باید کجا اجرا شود، بعد بقیه را بسپار به فریم‌ورک. + +## نکات کلیدی +- بپرس کار باید کجا اجرا شود: سرور کامپوننت جایی رندر می‌شود که داده هست، کلاینت کامپوننت جایی که کاربر. +- برگ‌های تعاملی را کلاینت نگه دار و سرور کامپوننت‌ها را به سمت ریشه‌های داده ببر. +- پراپ‌هایی که از مرز عبور می‌کنند داده‌ی سریال‌شده‌اند، پس تابع‌ها و instanceهای کلاس از آن رد نمی‌شوند. +- کامپوننتی که «هر دو» است را بشکن: یک پوسته‌ی کلاینت و یک بدنه‌ی سرور. +- بخش‌های فقط نمایشی را به سرور بسپار تا برایشان صفر جاواسکریپت زمان اجرا تحویل بدهی. + +## FAQ + +Q: چه چیزی یک کامپوننت را به کلاینت کامپوننت تبدیل می‌کند؟ +A: توانایی استفاده از هوک نیست، بلکه کاری است که باید انجام دهد. State و افکت، هندلر رویداد، APIهای مرورگر مثل geometry و media query و storage، و تعامل‌هایی که کاربر باید فوراً حس کند، کامپوننت را کلاینت می‌کنند. + +Q: وقتی پراپ از سرور کامپوننت به کلاینت کامپوننت می‌فرستم، چه چیزی خراب می‌شود؟ +A: پراپ‌هایی که از این مرز عبور می‌کنند به داده‌ی سریال‌شده تبدیل می‌شوند و تابع‌ها و instanceهای کلاس از آن عبور نمی‌کنند، پس شگفتی در همین مرز کمین می‌کند. کلاینت کامپوننت‌ها را نزدیک برگ‌های تعاملی نگه دار و سرور کامپوننت‌ها را به سمت ریشه‌های داده ببر. TEXT, ], [ @@ -1023,6 +1767,21 @@ INP در سایت‌های فارسی بیشتر از آنکه به کد مرب ## جمع‌بندی سئو تکنیکال برای وب‌های فارسی، بیش از آنکه کار فنی باشد، مجموعه‌ای از تصمیم‌های آگاهانه درباره‌ی متن و زبان است. وقتی فونت را سبک می‌کنید، محل سرور را با مخاطب هماهنگ می‌کنید و چیدمان راست‌به‌چپ را جدی می‌گیرید، Core Web Vitals خودبه‌خود بهتر می‌شوند. + +## نکات کلیدی +- یک خانواده‌ی فونت فارسی، حداکثر دو وزن، با woff2، subset و preload؛ بزرگ‌ترین عامل مخرب LCP همین است. +- تصویر LCP را هرگز lazy نکنید؛ AVIF یا WebP با ابعاد صریح بدهید و بقیه‌ی تصاویر را lazy کنید. +- ارتفاع خط را با متن فارسی واقعی تنظیم کنید، وگرنه پرش محتوا و CLS باقی می‌ماند. +- قبل از هر بهینه‌سازی سرعت، مشکل ایندکس را حل کنید: «ي» عربی، لینک‌های پارامتردار و داده‌ی ساختاریافته‌ی نامناسب. +- هاستینگ یا CDN داخلی برای مخاطب ایرانی معمولاً نتیجه‌ی واقعی بهتری می‌دهد، حتی اگر در تست بین‌المللی ضعیف‌تر باشد. + +## FAQ + +Q: سایت فارسی من امتیاز پایینی دارد؛ از کجا شروع کنم؟ +A: در بیشتر پروژه‌ها مشکل از فونت وب فارسی است، نه از کد. وزن‌های استفاده‌نشده را حذف کنید، فایل‌ها را به woff2 تبدیل و subset فارسی بگیرید و فایل اصلی را preload کنید. + +Q: چرا محتوای سایت بعد از بارگذاری بالا و پایین می‌پرد؟ +A: چون فونت وب با تأخیر می‌رسد و ارتفاع خط در فارسی با فونت جایگزین فرق محسوسی دارد. راه‌حل، خط ارتفاع دقیق برای فونت فارسی، preload فایل اصلی و رزرو فضا برای تصاویر و بلوک‌های اصلی است. TEXT, ], [ @@ -1093,6 +1852,21 @@ TEXT, ## چند توصیه‌ی پایانی سرعت یادگیری فنی را کند نکنید، چون نرخ شما تقریباً مستقیم به مهارتی است که شش ماه پیش داشته‌اید. روی مهارتی سرمایه‌گذاری کنید که تقاضا دارد و رقابت در آن کم است. و ساعتی از خود را برای دارایی بلندمدت کنار بگذارید؛ محصول، ابزار یا دوره‌ای که مال خودتان باشد، روزی سیستم کارفرمایی شما می‌شود. + +## نکات کلیدی +- نرخ ساعتی اهرم نیست؛ روی نتیجه‌ی قابل اندازه‌گیری با عدد تمرکز کنید، چون شواهد همیشه از کارت نرخ برنده می‌شود. +- سه نوع نمونه‌کار عمومی بسازید: مخزن گیت‌هاب، مقاله‌ی فنی و یک پروژه‌ی زنده. +- هر درخواستی خارج از اسکوپ را جداگانه قیمت‌گذاری کنید؛ بدون این کار دامنه‌ی پروژه باز می‌ماند و پروژه هرگز تمام نمی‌شود. +- هیچ پروژه‌ای را بدون قرارداد مکتوب و پیش‌پرداخت مرحله‌ای شروع نکنید و فقط از مسیرهای قانونی و شفاف استفاده کنید. +- انگلیسی فنی، در عمل بیشتر از هر مهارت دیگری نرخ شما را جابه‌جا می‌کند. + +## FAQ + +Q: از کجا شروع کنم وقتی سابقه‌ی فریلنسری ندارم؟ +A: راه‌حل نداشتن سابقه، ساختن سه نوع نمونه‌کار است، نه سه نوع رزومه: یک مخزن گیت‌هاب واقعی، یک مقاله‌ی فنی درباره‌ی همان چیزی که در آن قوی هستید، و یک پروژه‌ی زنده که همین حالا کار می‌کند و کسی می‌تواند امتحانش کند. + +Q: از کلاهبرداری چطور دور بمانم؟ +A: پرچم‌های قرمز ثابت‌اند: پروژه‌ی مبهم، بودجه‌ی غیرقابل‌باور، رد کردن تماس تصویری یا درخواست واریز وجه برای فعال‌سازی پلتفرم. هویت را تأیید کنید و هرگز به نشانی دیکته‌شده در تماس تلفنی پول نفرستید. TEXT, ], [ @@ -1147,6 +1921,21 @@ TEXT, ## تهدید واقعی چیست جمع‌بندی من این است: هوش مصنوعی تهدید نیست، ابزاری است که تعادل بازار کار را بازتعریف می‌کند. کسانی که از آن استفاده می‌کنند و مهارت عمیق را با آن ترکیب می‌کنند بهره می‌برند؛ کسانی که آن را نادیده می‌گیرند از پس نخواهند آمد. خطر اصلی از دست دادن شغل به‌خاطر هوش مصنوعی نیست؛ این است که شش ماه بعد از او جلو بماند. کاری که من انجام می‌دهم این است: یادگیری را متوقف نمی‌کنم، هوش مصنوعی را در کار روزمره جا می‌اندازم و روی چیزی تمرکز می‌کنم که انسانی می‌ماند، یعنی فهم مسئله، تصمیم‌گیری و مسئولیت‌پذیری. + +## نکات کلیدی +- راستی‌آزمایی کد تولیدشده را به مهارت اصلی خود تبدیل کنید؛ پرامپت‌نویسی حداقل است، نه تخصص. +- به سمت کارهایی بروید که به قضاوت انسانی نیاز دارند: فهم محصول، دیباگ، کارایی، امنیت و معماری. +- مبانی را جدی بگیرید؛ درک شبکه، سیستم‌عامل، ساختار داده و معماری مرز شما را می‌کشد. +- در انگلیسی بنویسید؛ مستندسازی فنی هم سازوکار یادگیری است و هم منبع پروژه‌های جدید. +- کل زنجیره را مالک شوید: مسئله، طراحی، ساخت، استقرار، اندازه‌گیری و نگهداری. + +## FAQ + +Q: هوش مصنوعی شغل برنامه‌نویسی را می‌گیرد؟ +A: تهدید اصلی از دست دادن شغل به‌خاطر هوش مصنوعی نیست؛ خطر واقعی این است که شش ماه بعد از آن جلو بمانید. هوش مصنوعی بخش بزرگی از کار را ارزان‌تر و سریع‌تر می‌کند و ارزش بخش انسانی را بالا می‌برد. + +Q: تازه‌کارها در ایران از کجا شروع کنند؟ +A: راه‌حل این نیست که از ابزار استفاده نکنید؛ با هوش مصنوعی آزمایش کنید، شکست بخورید و دیباگ کنید. همان تجربه‌ی دیباگ چیزی است که در سه سال اول کار حرفه‌ای به شما می‌دهد، فقط در شش ماه. TEXT, ], [ @@ -1208,6 +1997,21 @@ TEXT, ## حرف آخر سایت یک کسب‌وکار کوچک نباید طراح‌ها را تحت تأثیر بگذارد. باید روی یک گوشی ارزان در چند ثانیه باز شود، دقیقاً بگوید چه چیزی می‌فروشد و چطور به آن برسید، و شبیه یک کسب‌وکار واقعی با آدرس واقعی باشد. بقیه‌اش تزئین است. + +## نکات کلیدی +- چیدمان را موبایل‌محور و راست‌به‌چپ طراحی کنید؛ بیشتر ترافیک از بیوی اینستاگرام یا کانال تلگرام می‌آید. +- اسلایدر قهرمان، فونت‌های اضافه و هر افزونه‌ای که تنها کارش انیمیشن است حذف کنید. +- عناصر اعتماد همان چیزی است که تبدیل می‌کند: آدرس واقعی، نقشه، پروانه‌ی کسب‌وکار، نماد اعتماد، تلفنی که آدمی جواب می‌دهد و نظر واقعی مشتری. +- به‌جای سبد خرید، کاتالوگ با دکمه‌ی واتساپ بسازید تا خریدار داخل همان اپی کارش را نهایی کند. +- هدف من LCP زیر ۲.۵ ثانیه و ترجیحاً زیر ۱.۸ ثانیه، اندازه‌گیری‌شده روی اینترنت موبایل ایرانی محدود است. + +## FAQ + +Q: سایت کسب‌وکار کوچک من دقیقاً به چه چیزی نیاز دارد؟ +A: باید روی یک گوشی ارزان در چند ثانیه باز شود، دقیقاً بگوید چه چیزی می‌فروشد و چطور به آن برسید، و شبیه یک کسب‌وکار واقعی با آدرس واقعی باشد. قرار نیست طراح‌ها را تحت تأثیر بگذارد. + +Q: سبد خرید بسازم یا فرم رزرو؟ +A: بیشتر این کسب‌وکارها به کاتالوگ نیاز دارند، نه پلتفرم پرداخت: یک عکس، یک قیمت و دکمه‌ی واتساپ با پیام از پیش نوشته‌شده. این بهتر جواب می‌دهد چون خریدار سفارشش را داخل همان اپی که در آن است نهایی می‌کند. TEXT, ], [ @@ -1266,6 +2070,21 @@ TEXT, عدد حقوق فعلی‌تان را اول نگویید. بازه‌ی تأییدشده را بپرسید. به خاطر داشته باشید کارمند ایرانی از طریق فیش حقوق به تأمین اجتماعی کمک می‌کند که در مقایسه با صدور فاکتور فریلنسری، بخش قابل‌توجهی از بسته‌ی شما را تشکیل می‌دهد و آنجا کل مبلغ را خودتان می‌دهید. درباره‌ی پاداش، ساعات کاری، مرخصی و اینکه ابزار یا آموزش را پرداخت می‌کنند یا نه بپرسید. با کارفرمای خارجی، واحد پول، نرخ و شرایط پرداخت را پیش از شروع کار مکتوب کنید و همیشه پیش‌پرداخت بگیرید. وقتی هنوز به یادگیری سریع نیاز دارید استخدام را انتخاب کنید. وقتی مهارت و شبکه‌ی ارتباطی را دارید فریلنسری را. بازار این را برای شما تصمیم نمی‌گیرد. + +## نکات کلیدی +- ری‌اکت هنوز برای هر چیزی که شبیه محصول است انتخاب پیش‌فرض است، اما سطح انتظار برای جیونیور بدون پایه‌ی قوی بالا رفته. +- کل عرض استک را یاد بگیرید: لایه‌ی داده، تست واقعی، کارایی و قابلیت مشاهده، به‌علاوه‌ی بک‌اندی که ساعت دو بامداد بتوانید دیباگش کنید. +- مدل درآمدی را با مرحله‌ی شغلی هماهنگ کنید: استخدام در ابتدا، ترکیبی در میانه، فریلنسری فقط با حدود شش ماه ذخیره‌ی مالی. +- دو یا سه مطالعه‌ی موردی عمیق بسازید که هر کدام به یک عدد ختم شود؛ عدد بیشتر از اسکرین‌شات می‌نشیند. +- عدد حقوق فعلی‌تان را اول نگویید؛ بازه‌ی تأییدشده و سهم تأمین اجتماعی را در بسته حساب کنید. + +## FAQ + +Q: استخدام بهتر است یا فریلنسری؟ +A: انتخاب بیشتر به سطح و ذخیره‌ی مالی شما بستگی دارد تا به فریم‌ورک. زیر دو سال تجربه‌ی واقعی، استخدام را انتخاب کنید چون به بازبینی کد و راهنمایی نیاز دارید. ارشد با حدود شش ماه ذخیره‌ی مالی، فقط با قرارداد مکتوب و پیش‌پرداخت می‌تواند از حقوق جلو بزند. + +Q: دورکاری برای کارفرمای خارجی شدنی است؟ +A: بله، چند برابر به پول سخت پرداخت می‌کند و چند مهندس آن را مدیریت می‌کنند، اما برنامه‌ی پیش‌فرض نیست. موانع عینی است: تحریم‌ها، سختی دریافت پول، هم‌پوشانی با ساعات اروپا و مصاحبه به انگلیسی. TEXT, ], [ @@ -1326,6 +2145,487 @@ REST API برای محتوای استاندارد مسیر تمیزی است: ه ## موفقیت چه شکلی است قبل و بعد را روی صفحه‌های یکسان مقایسه کنید. روی سایت‌هایی که مهاجرت داده‌ام، LCP معمولاً از چهار یا پنج ثانیه به زیر دو ثانیه می‌افتد و INP حتی بیشتر بهتر می‌شود چون صفحه‌ساز حذف شده است. ترافیک باید بعد از جاافتادن ریدایرکت‌ها ثابت بماند و به‌خاطر سرعت رشد کند. قالب‌ها را یکی‌یکی مهاجرت دهید و اعتبار جست‌وجو را معامله نکنید. + +## نکات کلیدی +- قبل از هر تغییری خط پایه را ثبت کنید: همه‌ی آدرس‌های ایندکس‌شده با کد وضعیت، دوازده ماه داده‌ی سرچ کنسول و مقادیر LCP، INP و CLS هر قالب. +- صفحه‌سازها هستند که LCP و INP را می‌کشند، نه تصاویر و نه هاست؛ حذف همان‌ها بیشترین اثر را دارد. +- هر آدرس قدیمی را به معادل جدید نگاشت کنید و ساختار مسیر را یکسان نگه دارید؛ ۳۰۱ به نزدیک‌ترین معادل، نه به صفحه‌ی اول. +- اسلاگ‌های فارسی و عربی را دست‌نخورده و نرمال‌نشده نگه دارید؛ نرمال‌سازی لینک‌ها را می‌شکند و اعتبار جست‌وجو را از بین می‌برد. +- به‌صورت پیش‌فرض تولید ایستا کنید و بازتولید افزایشی را فقط جایی بگذارید که محتوا روزانه عوض می‌شود. + +## FAQ + +Q: چرا LCP سایت وردپرسی من پایین است؟ +A: در بیشتر موارد قالب و صفحه‌ساز مقصرند، نه تصویر و نه هاست؛ صفحه‌سازها بسته‌های بزرگ CSS و جاوااسکریپت، جی‌کوئری و درخت DOM عظیم تحویل می‌دهند. LCP معمولاً از چهار یا پنج ثانیه به زیر دو ثانیه می‌افتد. + +Q: وردپرس را CMS نگه دارم یا نه؟ +A: یا وردپرس را CMS هدلس نگه دارید و محتوا را در زمان بیلد بگیرید، یا همه‌چیز را به مارک‌داون، MDX یا CMS هدلس وارد کنید و صفحه‌های ایستا بسازید. بیشتر کارفرمایان من محتوای ایستا با یک ابزار ویرایش کوچک را انتخاب می‌کنند. +TEXT, + ], + [ + 'title' => 'معماری تمیز در لاراول', + 'slug' => 'clean-architecture-laravel-fa', + 'excerpt' => 'یک تقسیم‌بندی کاربردی برای لاراول که Eloquent را در مرز نگه می‌دارد، جهت وابستگی‌ها را رعایت می‌کند و از اضافه‌کاری در پروژه‌های کوچک جلوگیری می‌شود.', + 'category' => 'backend-fa', + 'tags' => ['laravel-fa', 'clean-code-fa'], + 'cover' => 'معماری تمیز در لاراول', + 'views' => 1940, + 'likes' => 136, + 'days_ago' => 8, + 'body' => <<<'TEXT' +# معماری تمیز در لاراول + +معماری تمیز معمولاً با انبوهی از اصطلاحات مثل Entity، UseCase، Port و Adapter آموزش داده می‌شود. این مفاهیم در تئوری مفیدند، ولی در پروژه‌های واقعی لاراول اغلب باعث اضافه‌کاری می‌شوند. هدف اصلی این نیست که همه قوانین را رعایت کنیم، بلکه این است که منطق کسب‌وکار را مستقل از فریم‌ورک نگه داریم تا کد پایه سال‌ها دوام بیاورد. + +## تقسیم‌بندی کاربردی + +یک راه ساده و آزموده‌شده، تقسیم کد به سه لایه اصلی است: Domain، Application و Infrastructure. این تقسیم‌بندی جهت وابستگی‌ها را واضح نگه می‌دارد بدون این‌که نیاز به بیست Namespace مختلف داشته باشیم. + +لایه Domain شامل مفاهیم اصلی کسب‌وکار است. Entityها، Value Objectها، Enumها و قوانین دامنه در این لایه قرار می‌گیرند. هیچ‌چیز در Domain نباید به لاراول، Eloquent، HTTP یا APIهای خارجی وابسته باشد. این لایه باید فقط PHP خالص باشد. + +لایه Application شامل UseCaseهاست؛ یعنی کاری که سیستم انجام می‌دهد. در این لایه جریان‌های کاری هماهنگ می‌شوند، قوانین کسب‌وکار اعمال می‌شوند و Interfaceهایی برای وابستگی‌های خارجی تعریف می‌گردند. Application فقط به Domain وابسته است و هیچ اطلاعی از Controllerها، Jobها یا دیتابیس ندارد. + +لایه Infrastructure لایه بیرونی است. جایی که لاراول زندگی می‌کند: مدل‌های Eloquent، Repositoryها، Jobها، کلاینت‌های HTTP، سرویس‌های تماس با شخص ثالث و کدهای مخصوص فریم‌ورک. Infrastructure Interfaceهای تعریف‌شده در Application را پیاده‌سازی می‌کند و هم به Application و هم به Domain وابسته است. + +## نگه داشتن Eloquent در مرز Repository + +یکی از رایج‌ترین اشتباهات این است که Eloquent را همه‌جا پخش می‌کنیم. Eloquent بسیار راحت است، ولی منطق کسب‌وکار را به اسکیمای دیتابیس و قابلیت‌های فریم‌ورک گره می‌زند. راهکار کاربردی این است که Eloquent را یک جزئیات پیاده‌سازی در نظر بگیریم. + +Interfaceهای Repository را در لایه Application تعریف کنید. مثلاً یک Interface به نام OrderRepository با متدهایی مثل findById یا save. سپس این Interface را در Infrastructure با استفاده از مدل‌های Eloquent پیاده‌سازی کنید. UseCaseها فقط به Interface وابسته‌اند، نه به خود مدل‌ها. این کار تست‌پذیری را بالا می‌برد و تعویض پیاده‌سازی را آسان می‌کند. + +همچنین از برگرداندن Collection یا Modelهای Eloquent از Repository به لایه Application خودداری کنید. آن‌ها را به Entityهای Domain یا DTOهای ساده نگاشت کنید. این کار مرز را تمیز نگه می‌دارد و از نفوذ Lazy Loading یا رفتارهای فریم‌ورک به داخل منطق کسب‌وکار جلوگیری می‌کند. + +## جهت وابستگی‌ها اهمیت دارد + +قانون اصلی این است: وابستگی‌ها باید به سمت داخل باشند. Infrastructure می‌تواند به Application و Domain وابسته باشد. Application فقط به Domain وابسته است. Domain به هیچ چیز بیرونی وابسته نیست. این همان اصل کلیدی برای جدا کردن کد از فریم‌ورک است. + +Controllerها، Routeها، Jobها و Commandها در Infrastructure قرار می‌گیرند. باید نقش هماهنگ‌کننده نازکی داشته باشند. آن‌ها UseCaseهای Application را صدا می‌زنند، درخواست HTTP را به DTO تبدیل می‌کنند و پاسخ را برمی‌گردانند. اگر Controller شما اعتبارسنجی، محاسبات پیچیده یا Queryهای سنگین انجام می‌دهد، احتمالاً آن منطق باید به Application یا Domain منتقل شود. + +## کی نباید لایه‌بندی را زیاده‌روی کنیم + +معماری تمیز هزینه دارد. برای یک پروژه CRUD کوچک، اضافه کردن سه لایه برای هر قابلیت، باعث پیچیدگی بی‌خودی می‌شود. اگر برنامه‌تان بیشتر ورود داده است و منطق کسب‌وکار کمی دارد، ساختار سنتی لاراول کاملاً کافی است. + +زمانی که باید لایه‌بندی اضافه کنیم، وقتی پیچیدگی افزایش می‌یابد. اگر قوانین کسب‌وکار غیرپیش‌پاافتاده دارید، چندین سرویس خارجی را یکپارچه می‌کنید یا احتمال دارد دامنه کسب‌وکار از انتخاب فریم‌ورک زنده‌تر بماند، این سرمایه‌گذاری ارزش دارد. اگر هنوز در مرحله اعتبارسنجی ایده هستید، ساده بمانید و هر‌زمان پیچیدگی پدید آمد، به‌تدریج به این مرزها نزدیک شوید. + +## ساختار پوشه‌ها به شکل کاربردی + +یک ساختار حداقلی و قابل‌نگهداری این است: در پوشه app، سه پوشه Domain، Application و Infrastructure ایجاد کنید. یا اگر ترجیح می‌دهید از src استفاده کنید. پوشه‌های پیش‌فرض لاراول را هر‌جا منطقی است نگه دارید، ولی منطق کسب‌وکار را خارج کنید. + +Domain می‌تواند شامل Entities، ValueObjects، Enums و Exceptionهای مخصوص دامنه باشد. Application شامل UseCases، Contracts (Interfaceها)، DTOs و Policies باشد. Infrastructure شامل Repositories، Services، Jobs، Http/Controllers و Adapterهای مخصوص فریم‌ورک باشد. + +این ساختار باعث می‌شود Namespaceها شفاف باشند و هر توسعه‌دهنده جدید بداند کد جدید را کجا قرار دهد. با رعایت جهت وابستگی‌ها، بدون نیاز به حفظ کردن تمام اصطلاحات پیچیده می‌توان کد تمیزی داشت. + +## نکات کلیدی + +- کد را به Domain، Application و Infrastructure تقسیم کنید تا منطق کسب‌وکار مستقل از فریم‌ورک بماند. +- Interfaceهای Repository را در Application تعریف کنید و پیاده‌سازی آن‌ها را با Eloquent در Infrastructure انجام دهید. +- مدل‌های Eloquent را در مرز به Entityهای Domain یا DTO نگاشت کنید و هیچ‌گاه آن‌ها را به داخل نفوذ ندهید. +- قانون وابستگی رو به داخل را رعایت کنید: Infrastructure به بیرون وابسته است و Domain به هیچ چیز وابسته نیست. +- فقط زمانی لایه‌بندی کنید که پیچیدگی کسب‌وکار آن را توجیه کند. پروژه‌های CRUD کوچک به معماری تمیز کامل نیاز ندارند. + +## FAQ + +Q: آیا باید Eloquent را کنار بگذارم؟ +A: نه. Eloquent ORM بسیار خوبی است. آن را در Infrastructure نگه دارید و پشت Interfaceهای Repository پنهان کنید. + +Q: این ساختار با معماری هگزاگونال یکی است؟ +A: ایده مشابهی دارد با نام متفاوت. هدف، جدا کردن هسته از وابستگی‌های خارجی با الگوی Port و Adapter است. این تقسیم‌بندی کاربردی همان هدف را بدون انبوه اصطلاحات دنبال می‌کند. + +Q: چطور این ساختار را تست کنم؟ +A: لایه Domain و Application را با تست‌های واحد سریع تست کنید (بدون لاراول). لایه Infrastructure را با تست‌های یکپارچگی و در صورت نیاز با دیتابیس یا Mock تست کنید. این کار حلقه بازخورد را سریع نگه می‌دارد. +TEXT, + ], + + [ + 'title' => 'یک گردش کار گیت و بازبینی کد که فراتر از پنج توسعه‌دهنده جواب می‌دهد', + 'slug' => 'git-branching-and-reviews-fa', + 'excerpt' => 'گلوگاه، استراتژی شاخه‌بندی نیست، کیفیت بازبینی کد است. شاخه‌های کوتاه‌عمر، کامیت‌های اتمیک، محافظت از main و چک‌های خودکار، یک تیم پنج‌نفره را به بیست‌نفره می‌رساند بدون آنکه بحثی بماند.', + 'category' => 'engineering-practices-fa', + 'tags' => ['git-fa', 'clean-code-fa'], + 'cover' => 'گردش کار گیت و بازبینی کد', + 'views' => 2340, + 'likes' => 155, + 'days_ago' => 17, + 'body' => <<<'TEXT' +# یک گردش کار گیت و بازبینی کد که فراتر از پنج توسعه‌دهنده جواب می‌دهد + +بیشتر تیم‌ها وقتی حوالی شش توسعه‌دهنده به بن‌بست می‌رسند، استراتژی شاخه‌بندی را مقصر می‌گیرند. چیزی که واقعاً با زیادشدن تعداد نفرات خراب می‌شود، کیفیت و سرعت بازبینی کد است. این همان گردش کاری است که روی هر پروژه نصب می‌کنم، به‌همراه دلیل هر تکه از آن. + +## شاخه‌های کوتاه‌عمر بر شاخه‌های بلندعمر می‌برند + +شاخه‌ای که سه هفته زندگی می‌کند، سه هفته تغییرات دیگران را با خود دارد که ندیده‌اید و در پایانش به یک merge دردناک ختم می‌شود. شاخه وجود دارد تا موازی کار کنید و بعد چیزی قابل بازبینی به نفر بعدی بدهید. + +- شاخه را همان روزی که شروع می‌کنید باز کنید و ظرف یک روز merge کنید. +- اگر زود merge نمی‌شود، یعنی تغییر بزرگ است. آن را بشکنید. +- شاخه‌های آزمایشی بلندعمر فقط وقتی جواب می‌دهند که آن کد در این فاصله منتشر نشود. +- شاخه‌ها را بعد از merge پاک کنید، وگرنه هیچ‌کس نمی‌فهمد کدام کار واقعی است. + +## trunk based در برابر feature branch، در عمل + +این دو مقابل هم نیستند. trunk based یعنی main همیشه قابل انتشار است، و شاخه کوتاه‌مدت در دل آن کاملاً اشکالی ندارد. از main برای چند ساعت کار شاخه می‌زنید، pull request باز می‌کنید و بعد از بازبینی merge می‌کنید. قطب مقابل را کنار بگذارید، جایی که هر توسعه‌دهنده یک شاخه شخصی چندماهه نگه می‌دارد. آن مدل تا اولین باری که دو نفر یک مایگریشن را لمس می‌کنند کار می‌کند. + +## کامیت‌هایی که اتمیک و قابل بازبینی‌اند + +کامیت واحد معناست نه واحد زمان. یک کار می‌کند، به‌تنهایی تست‌ها را پاس می‌کند و به‌تنهایی برمی‌گردد. همین ویژگی است که به شما bisect و revert تمیز می‌دهد. + +- بازآرایی کد را از تغییر رفتار جدا کنید. +- پیام کامیت را برای کسی بنویسید که شش ماه بعد bisect می‌کند. +- اینکه چرا تغییر رخ داد مهم‌تر از چیزی است که diff از قبل نشان می‌دهد. +- تاریخچه را کوتاه نگه دارید. ده کامیت از کار یک روزه اشکالی ندارد. + +## بازبینی خوب واقعاً چه چیزی را بررسی می‌کند + +بازبینی برای درستی و برای فهم مشترک است، نه برای قالب‌بندی. یک formatter در CI از قبل مالک indentation، ترتیب import و طول خط است. بازبیننده‌ای که حوصله‌اش را صرف همان‌ها می‌کند، مشکلات واقعی را دست‌نخورده رها می‌کند. + +- آیا همان کاری را می‌کند که تیکت گفته، شامل بخش‌های نانوشته، و نه بیشتر؟ +- با ورودی خالی، ورودی خیلی بزرگ و درخواست‌های هم‌زمان چه می‌شود؟ +- تست‌ها رفتار را پوشش می‌دهند یا فقط پیاده‌سازی را تکرار می‌کنند؟ +- آیا چیز حساسی در diff هست، مثل توکن، شناسه شخصی یا کوئری بدون محدودیت؟ +- آیا یک تازه‌وارد این را شش ماه بعد می‌فهمد؟ + +کامنت‌ها باید بگویند چه چیزی و چرا، نه فقط چه چیزی. بازبینی پر از خط‌های تکرارشده، نویز است و بازبینی نویزی سرسری خوانده می‌شود. + +## محافظت از main و خودکارسازی چک‌های خسته‌کننده + +ارزان‌ترین راه سریع‌کردن بازبینی، حذف سؤال‌هایی است که بازبیننده هرگز نباید مجبور به پرسیدنشان باشد. هر چیز مکانیکی جای CI است، چون یک آدم نباید یک دور بازبینی را صرف نبودن یک newline کند. + +- برای main پول‌ریک‌اینت با حداقل یک تأیید اجباری کنید. +- push مستقیم به main را ببندید. +- format، lint، typecheck و تست را status check اجباری کنید. +- پایپ‌لاین را زیر ده دقیقه نگه دارید و با رشد آن موازی‌سازی کنید. +- با squash یا rebase merge کنید تا main خطی بماند. + +## جمع‌بندی + +- برای ساعت‌ها شاخه بسازید نه هفته‌ها، چون هزینه بازبینی با اندازه diff رشد می‌کند. +- main را همیشه قابل انتشار نگه دارید و شاخه‌های کوچک را روزانه داخل آن merge کنید. +- کامیت‌های اتمیک با پیامی بنویسید که برای bisect آینده مفید باشد. +- رفتار و ریسک را بازبینی کنید و قالب‌بندی را به formatter بسپارید. +- هر چک مکانیکی را خودکار کنید تا توجه بازبیننده صرف درستی شود. + +## FAQ + +Q: توسعه trunk based برای تیمی که ماهی یک‌بار منتشر می‌کند کار می‌کند؟ + +A: بله، و برای انتشار ماهانه بهتر از شاخه‌های بلندعمر است. شما هر روز داخل main کد را merge می‌کنید و با تگ یا feature flag کنترل می‌کنید چه چیزی زنده برود، پس main قابل انتشار می‌ماند و خودِ انتشار طبق برنامه شما انجام می‌شود. + +Q: بازبینی‌های ما کند است، آیا باید دو تأیید اجباری کنیم؟ + +A: اولویت اول نیست. بازبینی کند معمولاً یعنی diff خیلی بزرگ است، تیکت مبهم است یا نویسنده دیر درخواست داده. اول هر سه را درست کنید و مطمئن شوید چک‌های مکانیکی در CI اجرا می‌شوند تا بازبیننده نقش لینتر را بازی نکند. بعد از آن سخت‌گیرتر کردن مایگریشن و کد احراز هویت منطقی است. +TEXT, + ], + + [ + 'title' => 'ایندکس‌های SQL که کوئری را سریع می‌کنند: راهنمای عملی با لاراول', + 'slug' => 'sql-indexes-database-performance-fa', + 'excerpt' => 'کندی یک اندپوینت لاراول تقریباً هیچ‌وقت از سرور نیست، از نبود ایندکس روی ستون کوئری است. اینجا یاد می‌گیرید EXPLAIN را چطور بخوانید، ترتیب ستون‌های ایندکس مرکب را چطور بچینید و با ایندکس روی کلید خارجی نوشتن را کند نکنید.', + 'category' => 'backend-fa', + 'tags' => ['database-fa', 'performance-fa'], + 'cover' => 'ایندکس و کوئری‌های سریع', + 'views' => 1960, + 'likes' => 128, + 'days_ago' => 9, + 'body' => <<<'TEXT' +# ایندکس‌های SQL که کوئری را سریع می‌کنند: راهنمای عملی با لاراول + +تقریباً هر اندپوینت کندی که برایش بررسی می‌کنم یک علت مشترک دارد: اسکن کامل جدولی روی ستونی که هیچ ایندکسی ندارد. لاراول نوشتن این کوئری را آسان می‌کند و فراموش‌کردنش را هم آسان، چون کسی متوجه نمی‌شود تا جدول از صد هزار ردیف عبور نکند. + +## ایندکس واقعاً چه کار می‌کند + +MySQL و PostgreSQL ایندکس‌ها را در یک درخت B ذخیره می‌کنند، درختی که کلیدهایش مرتب می‌ماند و برگ‌هایش کنار هم در حافظه می‌نشینند. همین یک ویژگی رفتار را توضیح می‌دهد: پیدا کردن یک کلید فقط چند صفحه را لمس می‌کند نه همه ردیف‌ها را، و دو شرط روی یک ستون با یک بار پیمایش درخت از ابتدای بازه تا انتهای آن سرو می‌شود. + +نیمه دیگر ماجرا هم مهم است: هر insert و هر update باید در هر ایندکس جدول هم نوشته شود، پس ایندکس مالیاتی است که روی نوشتن می‌پردازید تا خواندن سریع شود. + +## خواندن EXPLAIN بدون حدس زدن + +EXPLAIN را روی کوئری واقعی با پارامترهای واقعی اجرا کنید و از بالا به پایین بخوانید: نوع دسترسی، تعداد ردیف تخمینی، درصد فیلتر و ستون extra. + +- اسکن ترتیبی روی جدول بزرگ یعنی ایندکس قابل استفاده‌ای نیست. ستون و نوع مقدار را بررسی کنید. +- اسکن با ایندکس و تعداد ردیف تخمینی بسیار زیاد یعنی ایندکس برای بهینه‌ساز به‌اندازه کافی گزینشی نیست. +- عبارت rows removed by a filter معمولاً یعنی وایلدکارت یا عبارتی که قابل استفاده از ایندکس نیست. +- temporary table یا filesort یعنی ORDER BY از ترتیب ایندکس سرو نشد، پس اول ایندکس را درست کنید. +- زیرکوئری وابسته معمولاً به الگوی N به‌علاوه یک در Eloquent اشاره دارد، یک کوئری به‌ازای هر ردیف والد. + +## ترتیب ستون‌ها در ایندکس مرکب + +ایندکس چندستونی چند ایندکس جدا نیست، یک فهرست مرتب است و ترتیب ستون‌ها تعیین می‌کند کدام کوئری‌ها را سرو کند: اول شرط‌های تساوی، بعد یک ستون بازه، بعد ستون‌هایی که فقط برای مرتب‌سازی یا پوشش‌اند. + +- فیلتر روی ستون tenant و بازه created_at از ایندکس روی هر دو استفاده می‌کند، چون بازه در اولین ستون بازه‌ای متوقف می‌شود. +- فیلتر روی ستون کاربر و مرتب‌سازی بر اساس created_at نزولی هم کار می‌کند، چون موتور ایندکس را از عقب می‌خواند. +- اضافه‌کردن یک ستون تساوی در ابتدا معمولاً ایندکس تک‌ستونی قبلی را بی‌فایده می‌کند. +- جهتی را تست کنید که واقعاً کوئری می‌زنید، چون ترکیب صعودی و نزولی کاری را که موتور می‌تواند انجام دهد تغییر می‌دهد. + +## ایندکس پوششی + +ایندکس پوششی هر ستونی را که کوئری لازم دارد نگه می‌دارد، پس دیتابیس از خود ایندکس پاسخ می‌دهد و اصلاً به جدول دست نمی‌زند. این ستون‌ها را به ایندکس موجود اضافه کنید نه اینکه ایندکس تازه بسازید، و در ستون extra دنبال کلمه covering بگردید. نکته، هزینه نوشتن است، پس این روش برای چند کوئری داغ شماست. + +## کلید خارجی و هزینه ایندکس زیاد + +ستون کلید خارجی به دلیلی مستقل از راحتی کاربرد به ایندکس نیاز دارد: وقتی ردیفی حذف می‌شود، موتور باید ثابت کند هیچ ردیف فرزندی به آن اشاره نمی‌کند و بدون ایندکس این بررسی به اسکن کامل جدول تبدیل می‌شود در حالی که قفل نگه داشته شده است. + +- روی هر ستون کلید خارجی و هر ستون join ایندکس بگذارید، ارزان‌ترین برد کارایی در کل سیستم همین است. +- روی ستون‌هایی که فیلتر، مرتب‌سازی و join می‌شوند ایندکس بگذارید، اما ستون‌های فقط select را نه. +- در لاراول ایندکس‌ها را داخل مایگریشن بنویسید، نه در یک نشست کنسول دستی. +- در تست تمام کوئری‌ها را لاگ بگیرید، این کار بازگشت الگوی N به‌علاوه یک را قبل از پروداکشن می‌گیرد. + +## جمع‌بندی + +- ایندکس یک درخت B است، پس مرتب‌سازی و اسکن بازه‌ای ارزان می‌شود و هر نوشتن هزینه می‌دهد. +- قبل از دست‌زدن به کد، نوع دسترسی، تعداد ردیف تخمینی و extra را در EXPLAIN بخوانید. +- اول ستون‌های تساوی، بعد یک ستون بازه، بعد ستون‌های مرتب‌سازی. +- ایندکس پوششی بدون دست‌زدن به جدول پاسخ می‌دهد، پس روی مسیرهای داغ نگهش دارید. +- روی هر کلید خارجی ایندکس بگذارید و کل مجموعه را کوچک نگه دارید. + +## FAQ + +Q: چطور بفهمم کدام ایندکس‌ها واقعاً در پروداکشن استفاده می‌شوند؟ + +A: performance schema یا لاگ کوئری‌های کند ارائه‌دهنده را روشن کنید و کوئری‌های مهم را با تعریف ایندکس‌ها مقایسه کنید. در MySQL همین بخش شمارنده‌ای به‌ازای هر جدول برای ایندکس‌های استفاده‌نشده می‌دهد و حذف آن‌ها بعد از یک بازه ترافیک نماینده، امن‌ترین راه برداشتن ایندکسی است که فقط نوشتن را کند می‌کند. + +Q: ایندکس گذاشتن روی هر ستونی که در WHERE می‌آید کار بدی است؟ + +A: به‌محض اینکه حجم نوشتن مهم شود بد می‌شود، چون هر ایندکس با هر insert و update به‌روز می‌شود. به‌جایش بپرسید کدام کوئری‌ها پرتکرار یا کند هستند، چون یک ایندکس مرکب با ترتیب درست معمولاً چند شرط را با هم پوشش می‌دهد. +TEXT, + ], + + [ + 'title' => 'تایپاسکریپت فراتر از مقدمات: ژنریک‌ها، تایپ‌های کاربردی و حالت سخت‌گیرانه در پروژه‌های واقعی', + 'slug' => 'typescript-advanced-patterns-fa', + 'excerpt' => 'بیشتر تیم‌ها تایپاسکریپت را فقط به‌عنوان یک لینتر به کار می‌برند. ژنریک‌هایی که تایپ دامنه را حفظ می‌کنند، چند تایپ کاربردی مشخص و دو فلگ کامپایلر که از آن‌ها می‌گذرند، کامپایلر را به ابزار بازآرایی کد تبدیل می‌کنند.', + 'category' => 'frontend-fa', + 'tags' => ['typescript-fa', 'clean-code-fa'], + 'cover' => 'الگوهای تایپاسکریپت در پروژه واقعی', + 'views' => 2180, + 'likes' => 142, + 'days_ago' => 4, + 'body' => <<<'TEXT' +# تایپاسکریپت فراتر از مقدمات: ژنریک‌ها، تایپ‌های کاربردی و حالت سخت‌گیرانه در پروژه‌های واقعی + +بیشتر تیم‌ها تایپاسکریپت را برای تکمیل خودکار و برای اینکه دیگر اشتباه کلاسیک رشته در برابر عدد را تحویل ندهند اضافه می‌کنند. شش ماه بعد کد پر است از cast به any و از تنظیمات کامپایلری که هیچ‌کس جرئت دست‌زدن به آن را ندارد. این فاصله، مسأله واژگان است نه تلاش. + +## ژنریک‌هایی که واقعاً ارزش دارند + +یک ژنریک وقتی جای خود را توجیه می‌کند که یک منطق واحد باید چند شکل مختلف را بدون از دست رفتن اطلاعات تایپی هر کدام ادامه دهد. اگر انتهای پیاده‌سازی با یک cast بسته شود، یک تابع ساده می‌خواستید. + +- یک ریپازیتوری که تایپ موجودیت را یک بار می‌گیرد و همان را از همه متدها برمی‌گرداند. +- یک فرم‌ساز که هر فیلد تایپ مقدار خودش را اعلام می‌کند و نتیجه از روی همان فیلدها استنتاج می‌شود. +- یک کامپوننت جدول که تایپ سطر به‌همراه توابع دسترسی را می‌گیرد تا مرتب‌سازی در هر ستون درست بماند. +- یک ایونت‌امیتر تایپ‌شده که نگاشت آن هم محموله رویداد و هم نام‌های مجاز را تعریف می‌کند. + +دو قید بار اصلی را به دوش می‌کشند، چون کیدوف T فقط کلیدهایی را می‌پذیرد که تایپ واقعاً دارد و extends string ورودی را داخل یک خانواده شناخته‌شده نگه می‌دارد. + +## تایپ‌های کاربردی‌ای که واقعاً به آن‌ها نیاز دارید + +هیچ‌کس صد تایپ کاربردی را حفظ نمی‌کند. یک مجموعه کوتاه تقریباً همه نیاز را پوشش می‌دهد و ترکیب آن‌ها در یک别名 نام‌دار، بهتر از اختراع تایپ تازه برای هر مدل است. + +- Partial برای داده ارسالی ویرایش و مدل فرم. +- Pick و Omit برای ساخت DTO درخواست بدون تکرار نام فیلدها. +- ReturnType و Parameters تا یک هوک یک بار شکل خودش را تعریف کند. +- NonNullable برای مقدارهایی که از ستون nullable برمی‌گردند. +- Record برای دیکشنری تایپ‌شده به‌جای ایندکس‌سیگنچر باز. +- Awaited برای باز کردن پرامیس‌هایی که کلاینت‌ها برمی‌گردانند. + +## دو فلگ کامپایلر که همه از آن‌ها می‌گذرند + +حالت سخت‌گیرانه خط پایه است. ارتقایی که تقریباً هیچ‌کس روشن نمی‌کند noUncheckedIndexedAccess است و بیشترین باگ‌های واقعی را می‌گیرد، چون خواندن بیرون از محدوده رایج‌ترین منبع undefined در زمان اجراست. + +- دسترسی به آرایه و رکورد به مقدار یا undefined تبدیل می‌شود و خواندن خارج از محدوده دیگر کامپایل نمی‌شود. +- بررسی null در حالت سخت‌گیرانه مجبورتان می‌کند نبودن مقدار را مدیریت کنید، نه اینکه آن را با ادعای not-null سرپوش بگذارید. +- exactOptionalPropertyTypes جلوی دادن undefined به فیلد اختیاری را می‌گیرد. +- noImplicitOverride و فلگ خطای switch در ارث‌بری، اشتباه‌ها را جمع می‌کنند. + +روشن‌کردن این‌ها روی کدبیس قدیمی موج خطا می‌سازد، پس آن‌ها را برای ماژول‌های جدید فعال کنید و فایل‌ها را همان‌وقت که رویشان کار می‌کنید درست کنید. + +## یونیون‌های تفکیک‌شده بهتر از فیلدهای اختیاری‌اند + +آبجکتی با سه مقدار بولی و چهار فیلد nullable، هشت حالت معنادار دارد و کامپایلر هیچ‌کدام را بررسی نمی‌کند. یونیونی با یک فیلد وضعیت literal، ترکیب‌های نامعتبر را به خطای تایپی تبدیل می‌کند. + +- یک پرداخت را به‌صورت created، captured یا refunded مدل کنید، نه یک رشته وضعیت با فیلدهای nullable. +- جریان فرم را یونیونی از آبجکت‌های مرحله‌ای مدل کنید که هر مرحله فقط داده خودش را حمل می‌کند. +- با switch روی فیلد تفکیک‌کننده ناریکی ایجاد کنید تا یونیون داخل هر شاخه باریک شود. + +## کجا باید متوقف شویم + +برنامه‌نویسی در سطح تایپ سقفی دارد و عبور از آن، سریع‌ترین راهی است که یک تیم اعتمادش را به تایپ‌های خودش از دست می‌دهد. + +- تایپی نسازید که برایش توضیحی بلندتر از کدی که جایگزینش می‌شود لازم باشد. +- یک پیاده‌سازی را پشت پارامتر ژنریک پنهان نکنید تا پیاده‌سازی دومی واقعاً وجود داشته باشد. +- قواعد کسب‌وکار را در تایپ‌ها کدنویسی نکنید، حالت‌ها و روابط را کدنویسی کنید. +- داده بیرونی را یک بار در مرز ورودی پارس کنید و بعد همان تایپ را همه جا استفاده کنید. + +## جمع‌بندی + +- ژنریک را فقط وقتی اضافه کنید که شکل‌ها رفتار مشترک داشته باشند و قابل تشخیص بمانند. +- یک مجموعه کوتاه از تایپ‌های کاربردی را نگه دارید و آن‌ها را ترکیب کنید. +- اول noUncheckedIndexedAccess را روشن کنید و بعد بقیه فلگ‌های سخت‌گیرانه را فایل به فایل. +- خوشه‌های فیلد nullable را با یونیون‌های تفکیک‌شده جایگزین کنید. +- قبل از اینکه تایپ‌ها از منطق سخت‌تر خوانده شوند، متوقف شوید. + +## FAQ + +Q: کد سنگین در سطح تایپ کامپایلر را در کدبیس بزرگ کند می‌کند؟ + +A: گاهی بله، و این هزینه روی بزرگ‌ترین فایل‌ها می‌نشیند نه روی کل پروژه. تایپ‌های نگاشتی عمیق و کد ژنریکی که با یونیون‌های بزرگ نمونه‌سازی می‌شود، مقصر رایج‌اند. پس به‌جای حذف فلگ‌ها، چند تایپ پیچیده را ساده کنید. + +Q: حالت سخت‌گیرانه را یک‌جا روی کدبیس موجود فعال کنم؟ + +A: نه، یک‌جا نه. فلگ‌ها را برای پوشه‌های قدیمی از بیلد سراسری بیرون نگه دارید، برای ماژول‌های جدید بلافاصله اعمال کنید و خطاها را در دسته‌های کوچک و هر بار روی یک فایل رفع کنید. +TEXT, + ], + + [ + 'title' => 'وقتی مرورگر یک صفحه را باز میکند', + 'slug' => 'how-the-browser-loads-a-page-fa', + 'excerpt' => 'از DNS تا امتیاز ۹۰ Lighthouse، گام‌به‌گام بررسی می‌کنیم که مرورگر چطور صفحه را بارگذاری می‌کند و چه کارهایی باعث بهبود سرعت و تجربه کاربری می‌شود.', + 'category' => 'web-performance-seo-fa', + 'tags' => ['performance-fa', 'seo-fa'], + 'cover' => 'وقتی مرورگر یک صفحه را باز میکند', + 'views' => 2150, + 'likes' => 138, + 'days_ago' => 15, + 'body' => <<<'TEXT' +# وقتی مرورگر یک صفحه را باز میکند + +وقتی کاربر یک آدرس را در مرورگر تایپ می‌کند و Enter می‌زند، در کسری از ثانیه اتفاق‌های زیادی می‌افتد. فهمیدن این روند فقط تئوری نیست؛ به شما کمک می‌کند سایت‌های کند را دیباگ کنید، اولویت درست بدهید و هم تجربه کاربری و هم سئو را بهتر کنید. در ادامه قدم‌به‌قدم توضیح می‌دهیم چه می‌شود و هر مرحله چطور روی عملکرد اثر می‌گذارد. + +## DNS و برقراری اتصال اولیه + +اولین قدم، تبدیل نام دامنه به آدرس IP است. مرورگر اول کش خودش را چک می‌کند، بعد کش سیستم‌عامل، روتر و در نهایت سرورهای DNS. DNS کند باعث افزایش تأخیر می‌شود، مخصوصاً در شبکه‌های موبایل. + +بعد از پیدا شدن IP، مرورگر اتصال TCP برقرار می‌کند. برای سایت‌های HTTPS، این شامل دست‌داد TLS برای رمزنگاری هم می‌شود. TLS ۱٫۳ نسبت به نسخه‌های قدیمی تعداد دورهای لازم برای handshake را کاهش داده است. استفاده مجدد از اتصال (Connection Reuse) با keep-alive یا Multiplexing در HTTP/2 از تکرار این هزینه برای هر منبع جلوگیری می‌کند. + +## درخواست‌های HTTP و پروتکل‌های اتصال + +سایت‌های مدرن از HTTP/2 یا HTTP/3 استفاده می‌کنند. در HTTP/1.1 مرورگر محدودیت تعداد درخواست همزمان در هر دامنه داشت که باعث آبشاری شدن درخواست‌ها می‌شد. HTTP/2 اجازه می‌دهد چندین درخواست به‌صورت همزمان روی یک اتصال ردوبدل شوند. HTTP/3 از QUIC روی UDP استفاده می‌کند و Head-of-Line Blocking را کاهش می‌دهد و روی شبکه‌های ناپایدار عملکرد بهتری دارد. + +مرورگر ابتدا سند HTML را درخواست می‌کند. معمولاً فایل کوچکی است ولی کلید بارگذاری بقیه منابع است. نحوه تحویل آن توسط سرور، فشرده‌سازی (gzip یا Brotli) و هدرهای کش همگی روی زمان بارگذاری اولیه اثر می‌گذارند. + +## پارس HTML و ساخت DOM + +مرورگر هم‌زمان با دریافت بایت‌های HTML، آن را به Token تبدیل می‌کند و سپس درخت DOM را می‌سازد. این فرایند جریانی است؛ یعنی مرورگر می‌تواند قبل از دریافت کامل فایل، پارس را شروع کند. اما اگر به اسکریپت همگام (Synchronous) بدون defer یا async برسد، پارس HTML متوقف می‌شود. + +در حین پارس HTML، مرورگر به منابع خارجی مثل CSS، اسکریپت، تصویر، فونت و غیره اشاره‌هایی پیدا می‌کند. هرکدام باعث ارسال درخواست جدیدی می‌شود که بسته به پروتکل و اولویت، یا در صف می‌ماند یا بلافاصله ارسال می‌شود. + +## CSS حیاتی و منابع مسدودکننده رندر + +CSS به‌صورت پیش‌فرض رندر را مسدود می‌کند. مرورگر تا زمانی که CSSOM (مدل شی‌ء CSS) کامل نشود، نمی‌تواند محتوا را نمایش دهد. فایل‌های CSS بزرگ و بهینه‌نشده، زمان اولین نمایش (First Paint) را به تأخیر می‌اندازند. یک بهینه‌سازی رایج، استخراج و Inline کردن CSS حیاتی برای بخش بالای صفحه (Above-the-fold) و بارگذاری بقیه به‌صورت غیرهمگام است. + +جاوااسکریپت اثر بیشتری دارد. اسکریپت‌های همگام پارس HTML را مسدود می‌کنند و رندر را به تأخیر می‌اندازند. استفاده از script با type=module، defer یا async زمان اجرا را تغییر می‌دهد. defer ترتیب اجرا را حفظ می‌کند و بعد از تکمیل DOM اجرا می‌شود. async بلافاصله بعد از دانلود اجرا می‌شود و ترتیب را رعایت نمی‌کند. انتقال اسکریپت‌های غیرحیاتی به انتهای صفحه یا استفاده از defer، کلید بهبود عملکرد محسوس است. + +## Preload، Prefetch و Resource Hintها + +همه منابع همزمان کشف نمی‌شوند. مرورگر از یک Preload Scanner استفاده می‌کند تا منابعی را که در ادامه HTML آمده‌اند زودتر پیدا کند. همچنین می‌توانید Hintهای صریح بدهید: link rel=preload برای منابع حیاتی مثل فونت یا تصویر اصلی، preconnect برای برقراری زودتر اتصال به دامنه‌های مهم و prefetch برای منابعی که احتمالاً در صفحه بعد نیاز دارند. + +این Hintها به مرورگر کمک می‌کنند اولویت‌ها را درست تنظیم کند و بدون بار اضافی روی شبکه، تأخیرها را کاهش دهند. + +## تصاویر، فونت‌ها و پایداری چیدمان + +تصاویر معمولاً بزرگ‌ترین حجم بایت را دارند. بهینه‌سازی‌هایی مثل فرمت‌های مدرن (WebP، AVIF)، استفاده از srcset پاسخگو، Lazy Loading برای تصاویر خارج از دید و تعیین سایز مناسب، هم حجم را کاهش می‌دهند و هم از جابجایی چیدمان جلوگیری می‌کنند. رمزگشایی تصاویر بزرگ هم می‌تواند Main Thread را مسدود کند؛ استفاده از decoding=async و سایز مناسب کمک می‌کند. + +فونت‌ها هم اگر درست مدیریت نشوند باعث متن نامرئی یا جابجایی چیدمان می‌شوند. font-display: swap بلافاصله متن جایگزین را نمایش می‌دهد تا فونت وب بارگذاری شود و تجربه کاربری بهتری دارد. Preload کردن فونت‌های حیاتی احتمال FOIT (Flash of Invisible Text) را کاهش می‌دهد. + +Cumulative Layout Shift (CLS) زمانی رخ می‌دهد که محتوا بعد از رندر اولیه جابه‌جا می‌شود. رزرو کردن فضای لازم برای تصاویر، تبلیغات یا محتواهای داینامیک، مؤثرترین راه کاهش CLS است. + +## Pipeline رندر و Core Web Vitals + +وقتی CSSOM و DOM آماده شدند، مرورگر Render Tree می‌سازد، Layout محاسبه می‌کند، پیکسل‌ها Paint می‌شوند و لایه‌ها Composite می‌گردند. این فرایند فریم‌به‌فریم انجام می‌شود. Taskهای طولانی روی Main Thread باعث کند شدن تعامل کاربر می‌شوند. + +Core Web Vitals مستقیماً به همین Pipeline مربوط‌اند. Largest Contentful Paint (LCP) زمان بارگذاری بزرگ‌ترین عنصر قابل‌مشاهده مثل تصویر اصلی یا تیتر را اندازه می‌گیرد. Interaction to Next Paint (INP) پاسخگویی به ورودی کاربر را می‌سنجد. Cumulative Layout Shift (CLS) پایداری بصری را اندازه می‌گیرد. این معیارها تأثیر زیادی روی امتیاز Lighthouse و رتبه سئو دارند. + +## رسیدن به امتیاز ۹۰ Lighthouse + +رسیدن به ۹۰+ با تمرکز روی اصلاحات پراثر قابل‌دسترس است. تصاویر را بهینه کنید و با فرمت‌های مدرن سرو کنید. اسکریپت‌های غیرحیاتی را Defer یا Lazy Load کنید. CSS حیاتی را Inline کنید و منابع مسدودکننده رندر را کاهش دهید. از هدرهای کش و CDN برای کاهش Time to First Byte (TTFB) استفاده کنید. به دامنه‌های ثالث preconnect کنید و منابع حیاتی را preload کنید. در نهایت با رزرو فضای مناسب برای عناصر داینامیک، جابجایی چیدمان را به حداقل برسانید. + +کلید این نیست که همه‌چیز را انجام دهید، بلکه این است که آنچه مسیر حیاتی صفحه شما را مسدود می‌کند اصلاح کنید. با Chrome DevTools و Lighthouse پروفایل بگیرید، اندازه‌گیری کنید و مرحله‌به‌مرحله پیش بروید. + +## نکات کلیدی + +- DNS، TCP و TLS تأخیر اتصال ایجاد می‌کنند؛ از اتصال مجدد استفاده کنید و HTTP/2 یا HTTP/3 را به‌کار ببرید. +- پارس HTML جریانی است ولی با اسکریپت همگام متوقف می‌شود؛ برای JS غیرحیاتی از defer یا async استفاده کنید. +- CSS رندر را مسدود می‌کند؛ CSS حیاتی را Inline کنید و بقیه را بهینه بارگذاری کنید. +- منابع حیاتی را preload کنید و به دامنه‌های مهم preconnect کنید تا تأخیر کاهش یابد. +- تصاویر، فونت‌ها و چیدمان را بهینه کنید تا LCP، INP و CLS بهتر شوند و امتیاز Lighthouse افزایش یابد. + +## FAQ + +Q: بزرگ‌ترین عامل مؤثر روی LCP چیست؟ +A: معمولاً تصویر اصلی یا بزرگ‌ترین عنصر قابل‌مشاهده است. بهینه‌سازی سایز، فرمت و اولویت بارگذاری آن بیشترین تأثیر را دارد. + +Q: برای اسکریپت‌ها از async یا defer استفاده کنم؟ +A: برای اسکریپت‌هایی که به ترتیب DOM وابسته‌اند از defer استفاده کنید. برای اسکریپت‌های مستقل مثل آنالیتیکس که بلافاصله نیاز نیست از async استفاده کنید. + +Q: HTTP/3 چطور عملکرد را بهتر می‌کند؟ +A: HTTP/3 از QUIC روی UDP استفاده می‌کند، Head-of-Line Blocking را کاهش می‌دهد و در مواجهه با از دست رفتن بسته‌ها، مخصوصاً در شبکه‌های موبایل یا ناپایدار، سریع‌تر بازیابی می‌شود. +TEXT, + ], + + [ + 'title' => 'توسعه آزمونمحور و کد آزمونپذیر', + 'slug' => 'tdd-writing-testable-code-fa', + 'excerpt' => 'توسعه آزمونمحور را فقط در جاهایی به‌کار بگیرید که سرعت توسعه را افزایش می‌دهد و با سه لایه‌سازی مناسب، تست‌ها را سریع و کاربردی نگه دارید.', + 'category' => 'engineering-practices-fa', + 'tags' => ['testing-fa', 'clean-code-fa'], + 'cover' => 'توسعه آزمونمحور و کد آزمونپذیر', + 'views' => 1480, + 'likes' => 112, + 'days_ago' => 12, + 'body' => <<<'TEXT' +# توسعه آزمونمحور و کد آزمونپذیر + +بحث‌های زیادی درباره توسعه آزمونمحور وجود دارد. بعضی‌ها آن را یک قانون مطلق می‌دانند و بعضی‌ها آن را کاملاً بی‌فایده. واقعیت این است که توسعه آزمونمحور در برخی حوزه‌ها ارزش زیادی دارد و در برخی دیگر فقط اضافه‌کاری می‌شود. مهم‌ترین نکته این نیست که حتماً تست را اول بنویسید، بلکه هدف این است که کد آزمون‌پذیر بنویسید. + +## کجا توسعه آزمونمحور واقعاً مفید است + +بیشترین سود زمانی است که کد احتمال تغییر یا شکست زیادی دارد. قوانین کسب‌وکار بهترین مثال هستند. محاسبات قیمت، مالیات، تخفیف یا اعتبارسنجی‌ها معمولاً حالات زیادی دارند. اگر اول یک تست شکست‌خورده بنویسید، این قوانین صراحتاً مشخص می‌شوند و از بروز خطاهای رجگریشن جلوگیری می‌کنید. + +کارهای پارس کردن و تبدیل داده‌ها هم خیلی مفیدند. وقتی فرمت‌ها را تبدیل می‌کنید، داده استخراج می‌کنید یا ورودی‌ها را نرمال‌سازی می‌کنید، می‌توانید با توسعه آزمونمحور مرحله‌به‌مرحله پیش بروید و هر تست، رفتار را ثابت نگه می‌دارد تا با خیال راحت ریفکتور کنید. + +همچنین برای ریفکتور کردن کدهای قدیمی بسیار کمک می‌کند. اگر بتوانید قبل از تغییر، یک شبکه کوچک از تست‌های سریع دور یک ماژول بسازید، می‌توانید با اطمینان بیشتری آن را بازنویسی کنید. در نهایت هر جایی که ریسک رجگریشن بالاست، مثل احراز هویت، سطح دسترسی یا محاسبات مالی، ارزش سرمایه‌گذاری اولیه را دارد. + +## کجا فقط اضافه‌کاری می‌شود + +همه کدها نیاز به چرخه قرمز‌ـ‌سبز ندارند. نمونه‌های سریع رابط کاربری، اسکریپت‌های یک‌بارمصرف انتقال داده یا پروتوتایپ‌هایی که احتمالاً همان روز کنار گذاشته می‌شوند، معمولاً ارزش این کار را ندارند. همین‌طور کامپوننت‌های کاملاً نمایشی که رفتارشان ساده است و مدام تغییر می‌کند. + +هزینه فقط نوشتن تست نیست. هزینه نگهداری تست‌هایی است که دیگر رفتار مفیدی را پوشش نمی‌دهند و زمان زیادی می‌برد تا با تغییرات هماهنگ شوند. در این موارد بهتر است بعد از تثبیت رفتار، تست بنویسید یا تا زمان مشخص شدن طراحی، از نوشتن تست صرف‌نظر کنید. + +## قانون سه لایه برای آزمون‌پذیری + +ساده‌ترین راه برای نوشتن کد آزمون‌پذیر، تقسیم آن به سه لایه است. لایه منطق، شامل قوانین خالص کسب‌وکار بدون اثر جانبی است. این لایه بهترین مکان برای توسعه آزمونمحور است چون تست‌ها بلافاصله اجرا می‌شوند و هیچ وابستگی ندارند. + +لایه اثرات، مسئول ارتباط با بیرون است: دسترسی به دیتابیس، فراخوانی API، فایل‌سیستم، صف‌ها و سرویس‌های خارجی. این تست‌ها کندترند و معمولاً نیاز به Mock یا جایگزین دارند. این لایه باید نازک نگه داشته شود و پیچیدگی را به لایه منطق منتقل کنید. + +لایه رابط، با دنیای بیرون صحبت می‌کند؛ مثل کنترلرها، دستورات CLI یا هندلرهای رابط کاربری. این لایه فقط باید هماهنگ‌کننده باشد و داده‌ها را تبدیل کند. اگر بیشتر پیچیدگی در لایه منطق باشد، تست‌های لایه رابط کوچک می‌مانند و تست‌های یکپارچگی هدفمندتر خواهند بود. + +## نام‌گذاری و کیفیت آرگومان‌های آزمون + +تست‌ها مستنداتی برای توسعه‌دهندگان آینده هستند. نام خوب تست باید رفتار را توضیح دهد، نه پیاده‌سازی را. به‌جای testingFunctionReturnsTrue بهتر بگویید shouldApplyDiscountWhenSubtotalExceedsThreshold. این کار باعث می‌شود خطاها خواناتر باشند و هدف تست واضح‌تر باشد. + +Assertions هم به همان اندازه مهم‌اند. از Assertions دقیق و شفاف استفاده کنید و از بررسی جزئیات پیاده‌سازی مثل متدهای خصوصی یا ساختار داخلی اشیاء پرهیز کنید. روی رفتار قابل‌مشاهده تست کنید: ورودی، خروجی، اثرات جانبی مهم یا تغییراتی که از API عمومی قابل‌مشاهده‌اند. این کار تست‌ها را در برابر ریفکتور مقاوم‌تر می‌کند. + +## تست‌ها را سریع نگه دارید تا همیشه اجرا شوند + +سرعت مهم‌ترین ویژگی یک مجموعه تست کاربردی است. اگر اجرای تست‌ها چند دقیقه طول بکشد، فقط در CI اجرا می‌شوند. اگر چند ثانیه باشد، قبل از هر کامیت اجرا می‌شوند. همین تفاوت است بین پیدا کردن باگ زودهنگام و کشف آن چند ساعت بعد. + +برای سرعت بالا، در تست‌های واحد از دیتابیس واقعی، شبکه یا فایل‌سیستم استفاده نکنید. از Fake، Stub یا پیاده‌سازی در حافظه استفاده کنید. تست‌های کند را فقط برای مسیرهای حیاتی یکپارچگی نگه دارید و آن‌ها را جدا کنید. حلقه بازخورد سریع باعث می‌شود توسعه آزمونمحور سرعت توسعه را افزایش دهد نه کاهش. + +## نکات کلیدی + +- توسعه آزمونمحور را در جاهایی به‌کار بگیرید که رفتار به‌اندازه کافی پایدار است: قوانین کسب‌وکار، پارس کردن، ریفکتور و نواحی با ریسک رجگریشن بالا. +- در نمونه‌های سریع رابط کاربری، پروتوتایپ یا آزمایش‌های پر تغییر، آن را کنار بگذارید یا به بعد موکول کنید. +- از قانون سه لایه استفاده کنید: منطق، اثرات و رابط تا پیچیدگی جدا شود. +- تست‌ها را بر اساس رفتار نام‌گذاری کنید و روی نتایج قابل‌مشاهده Assert کنید، نه جزئیات داخلی. +- سرعت را اولویت دهید تا تست‌ها قبل از هر کامیت اجرا شوند و بازخورد سریع بماند. + +## FAQ + +Q: آیا همیشه باید اول تست بنویسم؟ +A: نه. وقتی نیازمندی‌ها آن‌قدر شفاف‌اند که می‌توان رفتار مورد انتظار را مشخص کرد، اول تست بنویسید. اگر طراحی هنوز در حال تغییر است، بهتر است اول پیاده‌سازی کنید و بعد از تثبیت شکل، تست اضافه کنید. + +Q: چه میزان پوشش تست کافی است؟ +A: روی مسیرهای حیاتی و حالات خاص تمرکز کنید، نه دنبال پوشش ۱۰۰٪. پوشش بالا روی کد پیش‌پاافتاده ارزش کمی دارد. پوشش خوب روی منطق حیاتی کسب‌وکار، از رجگریشن‌های واقعی جلوگیری می‌کند. + +Q: برای نوشتن کد آزمون‌پذیر حتماً باید از توسعه آزمونمحور استفاده کنم؟ +A: نه. توسعه آزمونمحور روشی است که معمولاً کد آزمون‌پذیر تولید می‌کند، اما می‌توانید به‌تدریج کد را به سمت آزمون‌پذیری ریفکتور کنید. هدف، کد آزمون‌پذیر با تست‌های سریع و معنادار است، نه رعایت دقیق همه قواعد. TEXT, ], ]; diff --git a/tests/Feature/Blog/PostTest.php b/tests/Feature/Blog/PostTest.php index 0280c57..1e0e972 100644 --- a/tests/Feature/Blog/PostTest.php +++ b/tests/Feature/Blog/PostTest.php @@ -28,7 +28,30 @@ class PostTest extends TestCase $response = $this->getJson("/api/blog/posts/{$post->slug}"); $response->assertStatus(200) - ->assertJsonStructure(['post', 'related_posts']); + ->assertJsonStructure(['post', 'related_posts', 'previous_post', 'next_post']); + } + + public function test_page_turn_links_stay_inside_the_reader_language() + { + Post::factory()->create(['slug' => 'older-topic', 'published_at' => now()->subDays(2)]); + Post::factory()->create(['slug' => 'older-topic-fa', 'published_at' => now()->subDays(2)]); + Post::factory()->create(['slug' => 'newer-topic', 'published_at' => now()->addDay()]); + Post::factory()->create(['slug' => 'newer-topic-fa', 'published_at' => now()->addDay()]); + $current = Post::factory()->create(['slug' => 'current-topic', 'published_at' => now()]); + $currentFa = Post::factory()->create(['slug' => 'current-topic-fa', 'published_at' => now()]); + + $response = $this->getJson("/api/blog/posts/{$current->slug}"); + + $response->assertStatus(200) + ->assertJsonPath('previous_post.slug', 'newer-topic') + ->assertJsonPath('next_post.slug', 'older-topic') + ->assertJsonMissing(['previous_post' => ['slug' => 'newer-topic-fa']]); + + $response = $this->getJson("/api/blog/posts/{$currentFa->slug}"); + + $response->assertStatus(200) + ->assertJsonPath('previous_post.slug', 'newer-topic-fa') + ->assertJsonPath('next_post.slug', 'older-topic-fa'); } public function test_can_create_post() diff --git a/tests/Feature/Blog/RealBlogContentSeederTest.php b/tests/Feature/Blog/RealBlogContentSeederTest.php index a6490d4..e70bbb1 100644 --- a/tests/Feature/Blog/RealBlogContentSeederTest.php +++ b/tests/Feature/Blog/RealBlogContentSeederTest.php @@ -25,9 +25,9 @@ class RealBlogContentSeederTest extends TestCase $this->seed(RealBlogContentSeeder::class); - $this->assertSame(12, Category::count()); - $this->assertSame(26, Tag::count()); - $this->assertSame(24, Post::count()); + $this->assertSame(14, Category::count()); + $this->assertSame(32, Tag::count()); + $this->assertSame(36, Post::count()); $post = Post::where('slug', 'core-web-vitals-practical-guide')->firstOrFail(); $this->assertSame($user->id, $post->author_id); @@ -40,16 +40,27 @@ class RealBlogContentSeederTest extends TestCase $faTwin = Post::where('slug', 'core-web-vitals-practical-guide-fa')->firstOrFail(); $this->assertNotNull($faTwin->published_at); - // Strict English/Persian mirror: the two versions always cover exactly - // the same topics, so no post exists in only one language. + // Every English post and every new topic pair resolve their Persian twin: + // the strict English/Persian mirror now spans 18 posts per language. $englishCount = Post::where('slug', 'not like', '%-fa')->count(); $persianCount = Post::where('slug', 'like', '%-fa')->count(); $this->assertSame($englishCount, $persianCount); + $this->assertSame(18, $englishCount); foreach (Post::where('slug', 'not like', '%-fa')->pluck('slug') as $slug) { $this->assertDatabaseHas('posts', ['slug' => $slug.'-fa']); } + // Deepened editing: every article ends with Key takeaways + FAQ sections + // in both languages, plus the new engineering-practices category pair. + foreach (Post::pluck('body') as $body) { + $this->assertStringContainsString('## FAQ', $body); + } + $this->assertDatabaseHas('categories', ['slug' => 'engineering-practices']); + $this->assertDatabaseHas('categories', ['slug' => 'engineering-practices-fa']); + $this->assertDatabaseHas('posts', ['slug' => 'typescript-advanced-patterns']); + $this->assertDatabaseHas('posts', ['slug' => 'typescript-advanced-patterns-fa']); + // featured_image is a VARCHAR(255) column; the generated og-image URLs // must never overrun it, or the seeder fails in production. foreach (Post::pluck('featured_image') as $image) { @@ -71,8 +82,8 @@ class RealBlogContentSeederTest extends TestCase $this->seed(RealBlogContentSeeder::class); $this->seed(RealBlogContentSeeder::class); - $this->assertSame(12, Category::count()); - $this->assertSame(26, Tag::count()); - $this->assertSame(24, Post::count()); + $this->assertSame(14, Category::count()); + $this->assertSame(32, Tag::count()); + $this->assertSame(36, Post::count()); } } \ No newline at end of file