今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

标签:#HP

找到 96 篇相关文章

AI 资讯

Laravel Middleware Execution Order Explained: Why Your Middleware Runs in the Wrong Order

Laravel middleware can be perfectly written and still behave unexpectedly. You may notice authentication running too late, permission checks failing, tenant initialization not working, logging middleware missing important data, or custom middleware executing in an order you didn't expect. In many cases, the middleware code itself is not the problem. The real issue is middleware execution order. Understanding how Laravel executes middleware is critical when building secure and scalable applications because every request passes through multiple layers before reaching your controller. Common Symptoms You may encounter problems such as: Authenticated users being treated as guests Permission middleware failing unexpectedly Tenant information not being available Request logging missing user details Rate limiting triggering before authentication Redirect loops after login Middleware appearing to be ignored completely These issues are often caused by middleware running in the wrong sequence. How Laravel Processes a Request A typical Laravel request follows this flow: Browser ↓ Global Middleware ↓ Middleware Group (Web/API) ↓ Route Middleware ↓ Controller ↓ Response ↓ Browser Each middleware layer can inspect, modify, allow, or block the request before it reaches your application logic. Because of this, execution order matters. Example Problem #1 Suppose you have two middleware: Authenticate User Log User Activity Your logging middleware expects an authenticated user. $user = auth()->user(); However, the log always shows null. Why? Because the logging middleware executes before authentication. The solution is ensuring authentication middleware runs first so user information is available when logging occurs. Example Problem #2 Multi-tenant applications often initialize tenant information through middleware. TenantMiddleware If another middleware accesses the database before tenant initialization, queries may use the wrong database connection. This can lead to: Incorrect data

2026-07-03 原文 →
AI 资讯

Migrating Laravel to Symfony Without Rewriting Your Domain

Book: Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You've been handed the ticket everyone dreads: move the app off Laravel and onto Symfony. Maybe the team standardized on Symfony. Maybe a Messenger-and-Doctrine shop acquired you. Maybe someone decided Eloquent's global scopes had cost enough Friday nights. The estimate comes back in quarters. Someone quotes the phrase "big rewrite" and the room goes quiet, because everyone remembers the last big rewrite. Here is the question that decides whether this is a quarter or a year: how much of your business logic imports the framework? If your PlaceOrder logic reaches into request() , calls Order::create() on an Eloquent model, and opens a transaction with DB::transaction() , then the framework is the application and you are rewriting the application. If your business rules sit in plain PHP classes that never heard of Laravel, then the migration is an adapter swap, and adapter swaps ship one route at a time. What the framework actually owns Strip a typical Laravel app down and you find three categories of code. The first is your domain and use cases: the rules about what an order is, what placing one means, when it can be cancelled. This is the part the business pays for. It should not import a framework at all. The second is glue that translates the outside world into calls on that logic: controllers, form requests, Eloquent models, queue jobs, service providers. This is framework-specific by definition. The third is infrastructure your code talks to through interfaces: the database, the queue, the mailer, the payment gateway. A framework migration only touches the second category. The trouble is that most Laravel apps let the first and

2026-07-03 原文 →
AI 资讯

Eloquent Events vs Domain Events: Why the Framework Hook Isn't Enough

Book: Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You wire a listener to Eloquent's saved event on the Order model. When an order is saved, send the confirmation email. It works in the demo. Then a support ticket lands: a customer got two confirmation emails for one purchase, and another got a refund receipt for an order that was never refunded. You dig in. The double email came from a background job that touched updated_at on the order to bump a cache. The bogus receipt came from an admin editing the shipping address, which saved the model, which fired saved , which ran a listener that assumed "saved means the order changed state." None of that was the customer's intent. All of it was persistence. That's the whole problem in one sentence. saved tells you a row hit the database. It does not tell you what happened in your business. What Eloquent events actually fire on Eloquent dispatches creating , created , updating , updated , saving , saved , deleting , deleted , and a few more. Every one of them is tied to a persistence operation on a single model. They fire because you called save() , update() , create() , or delete() , not because a business rule was satisfied. Here is the shape most teams start with: <?php namespace App\Models ; use Illuminate\Database\Eloquent\Model ; class Order extends Model { protected static function booted (): void { static :: updated ( function ( Order $order ): void { // "the order changed, email the customer" OrderMailer :: confirmation ( $order ); }); } } The listener assumes updated means "something the customer cares about changed." It doesn't. updated fires for any dirty column: a cached counter, a nightly touch() , an admin fixing a typo in t

2026-07-03 原文 →
AI 资讯

Laravel Nightwatch: First-Party APM and What It Actually Replaces

Book: Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You already run three tools that half-cover this job. Pulse gives you a live wall on a local route. Datadog runs an agent and prices on host and usage volume, so the bill scales with your infrastructure. Sentry catches the exceptions after they already hurt someone. And none of them can tell you the one thing you actually asked: the checkout request that took 900ms at 14:03 dispatched a job, that job ran a query, and the query is what timed out. Laravel Nightwatch reached general availability in 2025 as the framework's own APM, aimed straight at that gap. It is worth knowing exactly what it captures, what it charges, and where its knowledge of your app stops and yours begins. What Nightwatch actually is Two moving parts. A Composer package inside your app, and a separate agent process that ships the data. composer require laravel/nightwatch The package writes events to a local socket. The agent listens on 127.0.0.1:2407 , batches what it receives, and sends it to Nightwatch's cloud. Because the agent runs outside your request cycle, the request thread is not blocked waiting on a network call to a telemetry backend. Laravel puts the added cost at under 3ms per request ; take that as a starting figure and measure your own before you trust it. # environment token per app + environment NIGHTWATCH_TOKEN = your-env-token # start the collector (keep it running under a # process monitor: Forge daemon, Vapor, supervisor) php artisan nightwatch:agent # confirm it is alive and receiving php artisan nightwatch:status One detail that bites people: the agent has to be running for anything to arrive. In local dev you start it by hand. In product

2026-07-03 原文 →
AI 资讯

Laravel Precognition: Live Validation That Reuses Your Backend Rules

Book: Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You have two copies of the same rules. One lives in a StoreUserRequest on the server. The other lives in a Zod schema, or a Yup object, or a pile of required attributes, on the front end. They started identical. Then someone bumped the password minimum from 8 to 12 on the backend and forgot the client. Now the form says the password is fine, the user clicks submit, and a 422 bounces back with an error the UI never predicted. That drift is the whole reason live client-side validation is annoying to maintain. You are keeping two rulesets in sync by hand, and the sync breaks quietly. Laravel Precognition removes the second copy. The front end asks the server "would this pass?" before the user submits, and the server answers using the exact same validation rules the real request will run. What a precognitive request actually is A precognitive request is a normal HTTP request to your real endpoint, tagged with a Precognition: true header. Laravel sees the header, runs the route's middleware and validation, and then stops before your controller does any real work. It never writes a row. It never sends an email. It runs the rules and returns the verdict. Success comes back as 204 No Content with a Precognition-Success: true header. Failure comes back as a normal 422 with the same JSON error bag your form submit would produce. Same rules, same messages, same field names. There is no second schema to drift. The lifecycle is worth holding in your head: Front end sends the form state to the real URL with Precognition: true . Middleware runs. FormRequest validation runs. Laravel short-circuits: your controller body never executes. Response is

2026-07-03 原文 →
AI 资讯

Building a typed CMS for business data with PHP, OpenAPI, and MCP

In my previous article, I introduced the NeNe series: a family of small, self-hosted business tools for teams operating in Japan. Previous article: https://dev.to/hideyukimori/i-am-building-self-hosted-business-tools-for-small-teams-in-japan-4i26 This article is a deeper look at one of those tools: NeNe Records . Repository: https://github.com/hideyukiMORI/nene-records NeNe Records is an API-first typed CMS and flexible entity platform built on NENE2 , my small PHP framework for AI-readable business APIs. It is not trying to be a WordPress clone. It is not trying to run WordPress plugins or themes. The goal is different: manage business data and public content through typed schemas, documented APIs, and clear AI tool boundaries. Why not just use WordPress? WordPress is useful. It has proven that a generic content model can support blogs, pages, shops, media, and many small business workflows. But when I think about business data, a few problems keep coming back: untyped metadata plugin-specific data shapes hooks and filters that can change behavior from many places API contracts that depend heavily on plugins AI integrations that may not know where the real application boundary is The postmeta model is flexible, but it often becomes stringly typed storage. That is fine for many websites. But for business data, I usually want the API to know more: this field is text this field is an enum this field is an image this field is a relation this field is required this record belongs to this organization this operation requires this role That is the space where NeNe Records lives. Typed records instead of metadata chaos The core model is simple: Entity Type -> Field Definition -> Record An Entity Type defines what kind of data exists. Examples: posts pages products events internal documents A Field Definition describes the shape of a field: text markdown html blocks int enum bool datetime image file relation A Record is the actual data. The important part is that the schema

2026-07-02 原文 →
AI 资讯

Bimaaji: agent-safe mutations for Waaseyaa

Ahnii! If you let an AI agent modify your application, the agent needs more than a text editor. Raw str_replace on a PHP file passes a lot of tests and still breaks things an hour later in production, because the tool has no idea what the file actually represents. Bimaaji is the Waaseyaa package that gives agents a structured path from "I want to add a field to this entity" to a reviewable patch that a community's sovereignty rules have already vetted. This post walks through what shipped in waaseyaa/bimaaji and why each piece exists. Prerequisites: familiarity with Waaseyaa's package layout, PHP 8.4+, and the idea that an application has more state than the filesystem (routes, entities, introspection metadata). Why not just let the agent edit files The failure mode you want to avoid: an agent reads a prompt like "add a published_at field to the Post entity," does a reasonable-looking edit to Post.php , and leaves the rest of the app inconsistent. The migration is missing. The JSON:API resource doesn't expose the field. The admin panel still doesn't know it exists. The sovereignty profile that was supposed to block the change on a local-only deployment never got consulted. Each of those is a different subsystem. A good agent can write a correct edit to any one of them. What a filesystem-level tool cannot do is ensure the edit is coordinated across all of them and is allowed under the community's posture. Bimaaji separates that problem into three stages: introspect, propose, patch. The pipeline The package description (from packages/bimaaji/composer.json ) spells it out: application graph introspection and agent-safe mutation for Waaseyaa. The flow is: Introspection → ApplicationGraph → MutationRequest → Validator → PatchGenerator → PatchSet An agent reads the graph, submits a structured mutation request, a validator checks it against sovereignty rules, and the patch generator returns reviewable diffs. Nothing touches the filesystem until a human (or a higher-level w

2026-07-02 原文 →
AI 资讯

Integrating Claude/OpenAI API into a Laravel App: A Practical Guide

After 12+ years of building PHP applications, I recently added AI-powered features to a production Laravel dashboard — automatic report summaries generated from raw analytics data. What surprised me wasn't how hard it was. It was how little good PHP-focused content exists on this topic. Almost every LLM tutorial assumes you're writing Python. So here's the guide I wish I had: integrating the Claude API and OpenAI API into a Laravel app, with a clean architecture you can actually ship to production. What we'll build: a ReportSummaryService that takes raw data and returns a human-readable summary — with a driver pattern so you can switch between Claude and OpenAI with one config change. Step 1: Get Your API Keys Claude: Sign up at the Claude Console , generate a key under Account Settings. OpenAI: Get a key from the OpenAI Platform . Add them to your .env : AI_PROVIDER=claude ANTHROPIC_API_KEY=sk-ant-xxxxx ANTHROPIC_MODEL=claude-sonnet-4-6 OPENAI_API_KEY=sk-xxxxx OPENAI_MODEL=gpt-5-mini ⚠️ Never hardcode API keys. Never commit them. If you've ever pushed a key to Git, rotate it immediately. (You know this. I'm saying it anyway.) Now register them in config/services.php — this is the Laravel way, so you can use config() everywhere and benefit from config caching: 'anthropic' => [ 'key' => env ( 'ANTHROPIC_API_KEY' ), 'model' => env ( 'ANTHROPIC_MODEL' , 'claude-sonnet-4-6' ), ], 'openai' => [ 'key' => env ( 'OPENAI_API_KEY' ), 'model' => env ( 'OPENAI_MODEL' , 'gpt-5-mini' ), ], 'ai' => [ 'provider' => env ( 'AI_PROVIDER' , 'claude' ), ], Step 2: Understand the Two APIs (They're 95% Similar) Both are simple REST APIs. You POST JSON, you get JSON back. Claude (Messages API): POST https://api.anthropic.com/v1/messages Headers: x-api-key: YOUR_KEY anthropic-version: 2023-06-01 content-type: application/json OpenAI (Chat Completions API): POST https://api.openai.com/v1/chat/completions Headers: Authorization: Bearer YOUR_KEY content-type: application/json The key differenc

2026-07-02 原文 →
AI 资讯

Maintaining WordPress sites behind HTTP Basic auth — Playwright, urllib, and encrypted credentials

It's pretty common to throw a layer of HTTP Basic auth on a WordPress site: a staging environment before launch, an internal test instance only employees should see, or any environment that wants an extra gate before the WordPress login screen itself. From a maintenance-tool point of view, this setup creates a peculiar "half-working, half-broken" asymmetry. The SSH/WP-CLI side runs fine. But everything HTTP-based — visual checks, thumbnail generation, browser-based fallback updates — hits 401 and dies. This post walks through how we resolved that asymmetry. What was breaking — two parallel paths, both blocked A maintenance tool actually touches a Basic-auth-protected site through two distinct paths: Playwright path : visual checks, thumbnail capture, browser fallback updates when SSH isn't available. browser.new_context() → navigation → screenshot urllib path : HTTP status checks (pre/post-update 200/5xx/4xx monitoring, rollback decisions) With no credentials, both paths see a 401 Unauthorized from the protected site. The Playwright symptom is the obvious one: the screenshot you save is the browser's "authentication required" dialog. The thumbnail grid fills with dark auth-prompt images, and you start wondering whether anything actually works. The urllib symptom is much worse — it silently breaks rollback decisions . A 401 baseline followed by another 401 after the update looks like "nothing changed = healthy." Real failures can hide behind that match, and the rollback that should have fired never does. The design — consolidate credential extraction into one helper When the same credentials need to flow through multiple code paths, picking them out of the site dict separately at each call site invites format-mismatch and missed-update bugs. So the first thing we did was build a small core/basic_auth_utils.py module that owns every form of credential extraction . # core/basic_auth_utils.py def get_basic_auth_tuple ( site ): """ Return (user, password), or None if not

2026-07-01 原文 →
AI 资讯

How to Know What Breaks Before You Upgrade WordPress to PHP 8.4

Every WordPress developer knows the feeling. A host emails: "PHP 7.4 reaches end of life — we're moving you to 8.x." Or you finally want the performance and security of PHP 8.4. You stage it, click upgrade, and… white screen. Somewhere in the 40 plugins and 3 themes on the site, something called a function PHP removed years ago — and now the whole site is down. The frustrating part: the broken code is almost never yours. It's buried in third-party plugins and themes you didn't write and can't easily read. So how do you find out what breaks before you upgrade, instead of after? This post walks through exactly that, using an open-source tool called Pressready . Why "just test it on staging" isn't enough Staging tells you that something broke, rarely what or where — and only for the code paths you happen to exercise. A fatal in an admin screen or a checkout edge case you didn't click won't surface until a real user hits it. You need something that reads all the code statically and reports every risky symbol, whether or not that path runs during your manual test. That's a job for static analysis across the whole stack. Two kinds of "breakage": PHP and WordPress Upgrades break sites along two axes, and a good audit covers both: The PHP axis — language features that get removed (e.g. create_function() is gone in PHP 8.0, each() in 8.0) or change behaviour between versions. The WordPress axis — core APIs that WordPress deprecates or removes from one release to the next. Pressready checks both in a single pass: it runs PHPCompatibility for the PHP axis and a custom PHP_CodeSniffer sniff — driven by a generated dataset of WordPress core deprecations — for the WordPress axis. Install it (pick whatever fits your setup) No Composer in the project? Use the standalone PHAR or Docker: # Standalone PHAR — single self-contained file, just needs PHP curl -L https://github.com/itzmekhokan/pressready/releases/latest/download/pressready.phar -o pressready.phar chmod +x pressready.phar #

2026-06-30 原文 →
AI 资讯

Stop Writing the Same Laravel Boilerplate: Generate a Complete Module with One Artisan Command

Stop Writing the Same Laravel Boilerplate: Generate a Complete Module with One Artisan Command Every Laravel developer has experienced this. You start implementing a new feature and immediately create the same files you've created dozens of times before: Model Migration Repository Service Form Request API Resource Policy Filter Status Enum Feature Tests Unit Tests Swagger/OpenAPI annotations The process is repetitive, time-consuming, and easy to get wrong. The Problem While Laravel provides excellent generators, building a production-ready API module still requires running many Artisan commands and wiring everything together manually. For large projects following Repository and Service Layer architectures, this becomes even more repetitive. The Solution I built Laravel Base , an open-source package that generates an entire production-ready module from a single command. php artisan make:module Product The generated module includes: ✅ Model ✅ Migration ✅ Repository Pattern ✅ Service Layer ✅ Form Requests ✅ API Resources ✅ Filters & Pagination ✅ Policies ✅ Status Enums ✅ Swagger/OpenAPI annotations ✅ Feature Tests ✅ Unit Tests Modern Development Experience The package is actively maintained and includes: Laravel 10–13 support PHP 8.1–8.4 compatibility GitHub Actions CI PHPStan static analysis Laravel Pint code style Automated releases Repository automation Why I Built It After working on multiple Laravel projects, I noticed I was spending too much time generating the same project structure instead of focusing on business logic. I wanted a tool that lets developers start implementing features immediately rather than setting up folders and classes. Feedback Welcome Laravel Base is open source, and I'd love to hear your thoughts. GitHub Repository: https://github.com/MuhammedMSalama/LaravelBase Packagist: https://packagist.org/packages/muhammedsalama/laravel-base The package was recently featured by Laravel News, and I'm continuing to improve it based on community feedbac

2026-06-30 原文 →
AI 资讯

When paramiko's defaults silently get your IP banned — the look_for_keys and allow_agent trap

One day a multi-site administrator reported a strange bug: "After running the app's SSH connection test 2-3 times, my IP can't reach SSH on that server for a long while ." The errors came back as Connection refused or Connection closed by ... . The server wasn't down, and SSH from a different IP worked fine. The source IP was being temporarily banned at the server. Two external investigation reports gave the cause: server-side protection mechanisms ( fail2ban or PerSourcePenalties in OpenSSH 25+) detect short-windowed authentication failure spikes and temporarily ban the source IP. But the user had only clicked the test button 2-3 times — why were failures "spiking"? The answer turned out to be paramiko's default behavior . paramiko's default — trying many keys per connection paramiko.SSHClient.connect() defaults two options to True : client . connect ( ' host ' , pkey = my_key , # The following are True by default: # look_for_keys=True, # also try ~/.ssh/id_* files # allow_agent=True, # also try ssh-agent registered keys ) When the explicitly passed pkey fails, paramiko falls back through ssh-agent registered keys → ~/.ssh/id_* files → password auth in order. Convenient for developers with a single key. Disastrous for a multi-site administrator: The SSH agent has multiple per-site keys registered ~/.ssh/ holds several id_rsa / id_ed25519 files A single connect call ends up trying 5-10 keys in sequence That blows past the server's MaxAuthTries (default 6) on a single connection So what looked to the user like "one connection test" was being seen by the server as " a suspicious IP racking up 5-10 auth failures in a row ." Repeat that 2-3 times and the protection mechanism declares the IP "exceeded threshold" and bans it. The fix — look_for_keys=False and allow_agent=False paramiko exposes options to scope key trial. We set them explicitly in connect_kwargs : connect_kwargs = { ' pkey ' : my_key , ' look_for_keys ' : False , # don't try ~/.ssh/id_* ' allow_agent ' : F

2026-06-30 原文 →
AI 资讯

Resolve the tenant from the user, not the request

TL;DR A multi-tenant app was resolving the active tenant from the request (subdomain/header) instead of the authenticated user . That makes the client the source of truth for "which tenant am I" — the wrong place for it. Fix: derive the tenant from the user's organization membership, enforce it in middleware, and fail closed. One test locks the behaviour. The bug, in one sentence The request was telling the app which tenant to load, and the app believed it. In a multi-tenant SaaS, every query is implicitly scoped: "give me this tenant's dashboards." If the tenant ID comes from something the client controls — a subdomain, a header, a route param — then the scoping is only as trustworthy as the client. That's a leak waiting to happen. Where the trust should live Think of it like a building pass. The request is someone saying "I'm here for floor 9." The membership record is the pass that says which floors you're actually allowed on. You check the pass, not the claim. Before After Source of truth request (subdomain / header) user's organization membership Who decides the tenant the client the server Failure mode user can land in a tenant they don't belong to resolution fails closed Testable? hard — depends on request shape yes — depends on the user The shape of the fix Resolve the tenant from the authenticated user's organization, in one middleware, before anything tenant-scoped runs: final class SetTenantContext { public function handle ( Request $request , Closure $next ): Response { $org = $request -> user () ?-> currentOrganization (); // No org, no tenant context. Fail closed, never guess. abort_if ( $org === null , 403 , 'No organization context.' ); Tenancy :: setCurrent ( $org -> tenant ); // server-derived, not request-derived return $next ( $request ); } } The key line isn't the setCurrent() — it's that the value comes from $request->user() , not from $request . The user is authenticated; the subdomain is not. request ──> [auth] ──> [SetTenantContext] ──> tena

2026-06-30 原文 →
AI 资讯

When a KPI reads 163 billion instead of 819

TL;DR A metrics engine had two query paths — a SQL push-down for big datasets, an in-memory aggregator for small ones. They drifted. The push-down path bound a metric parameter but never added it to the WHERE . With several metric series in one dataset, every query summed across all of them. A KPI that should read 819 read 163,667,603,769 . Fix: put the metric_key predicate in the shared base WHERE so every compile path inherits it, and regression-test both paths assert it. The setup: two paths, one contract A lot of analytics layers compute the same number two ways. For a big dataset you push the aggregation down to the database. For a small one — a preview, a draft dashboard — you pull the rows and aggregate in memory. Faster path, correct path. Both are supposed to return the same value. That's the contract. The dataset stores rows keyed by a metric_key , because one dataset can hold several series at once — say a plain row count and a count-distinct. Each series lives in the same table, told apart only by its key. The bug: a bound param is not a filter The in-memory aggregator filtered by metric_key correctly. The SQL compiler bound a metric parameter into the query... and never referenced it in the WHERE . With a single series in the dataset, it worked by accident — there was nothing else to sum. Add a second series and the math quietly breaks: the query sums across every series. In this case the second series stored hashed values around 1.9 billion each, so the KPI ballooned from 819 to 163 billion. Before After metric value bound, unused bound WHERE predicate (none on metric) metric_key = {metric:String} 1 series in dataset correct (by luck) correct N series in dataset sums across all isolated The lesson is small and easy to miss: binding a parameter only makes the value available — it does nothing until a predicate references it. When one path already returns sane-looking numbers, nobody goes looking. The real fix is parity, not a patch You could bolt the pr

2026-06-30 原文 →
AI 资讯

Contact Form 7 sent the email — but did it arrive? You have no way to know

Contact Form 7 runs on millions of sites for a good reason: it's free, light, and gets out of your way. I shipped it on client sites for years. The problem isn't that CF7 is bad — it's that it answers exactly one question ("did the form submit?") and stays completely silent on the one that actually matters in production: did the notification arrive? Here's the call every developer who maintains WP sites has taken at least once: "I filled in your contact form last week and never heard back." You check. The form is fine. JavaScript fires, the success message shows, no console errors. CF7 did its job — it handed the message to wp_mail() and forgot it ever existed. There's no record the submission happened, and no log of whether the email was delivered, bounced, or quietly dropped by the host's unauthenticated sendmail. The lead is just gone, and you have nothing to debug with. The three gaps that bite in production No submissions database. CF7 sends an email and discards the data. If the email fails or lands in spam, the submission never existed. (Flamingo helps, but it's a bolt-on — separate screen, no filtering or export out of the box, not tied to your form config.) No delivery log. You can't tell whether mail was sent, rejected, or bounced. "I never got it" has no audit trail to check against. No native block. CF7 is still a shortcode — [contact-form-7 id="123"] . You can't drop it into a block template, control its layout with block spacing, or edit it inline in Gutenberg. You paste a shortcode and hope. None of these are dealbreakers for a throwaway contact form. All three are dealbreakers when a missed submission is a missed sale. Migrating without rebuilding by hand The reason most people put off switching isn't the feature gap — it's the thought of rebuilding every form field by field. That's the part I wanted to skip. The migration path I use reads CF7's stored form definitions directly and recreates them as native forms. What comes across automatically: All

2026-06-29 原文 →
AI 资讯

When SSH commands hit a csh login shell — wrapping every command in /bin/sh -c across the codebase

One day a user reported an oddly asymmetric bug. In the "add new site" modal, picking an SSH profile and clicking "auto-detect WordPress install path" always failed with "no path found." But clicking the WP-CLI path test button on the same SSH connection worked fine . Same credentials, same host — one succeeded, the other failed. Tracing it down, the culprit was an old foe: csh / bash incompatibility on the server side . This post walks through the fix, sweeping the same bug across the rest of the codebase, and the static-analysis test we added to keep it from coming back. The smoking gun — find: 2: unknown primary or operator The server-side error log gave it away: find: 2: unknown primary or operator find itself is POSIX-standard, but it was dying with a mysterious 2 argument. That 2 is the leading number of 2>/dev/null — a redirect that was being passed as a literal argument to find because the shell never interpreted it as a redirect in the first place . Note: 2>/dev/null is the standard way to silently discard stderr in Bourne shell (sh) and bash. csh (C shell) uses different syntax and doesn't recognize it. Sakura Internet defaults users to csh We've documented this before in the four-host investigation of why WP-CLI doesn't run : on Sakura Internet (Japanese host), the default user login shell is csh / tcsh , not bash. This collides with how paramiko (Python's SSH library) works: exec_command runs the command through the user's login shell. Sending find ... 2>/dev/null to a Sakura host means csh tries to interpret it and chokes . That's the real error. The bash/sh idioms that fall over on csh include: 2>/dev/null (redirect) [ -f path ] (test syntax) for X in ...; do ... done (loop) cmd1 && cmd2 (short-circuit) \( ... \) (subshell) These all blow up with "unknown primary or operator" or "Missing }" on csh. "I fixed one site, so they're all fixed" — but they weren't This wasn't our first encounter with this issue. A few release rounds earlier, we'd noticed test

2026-06-28 原文 →
AI 资讯

Seu código de validação de CPF tá gritando por socorro (e você nem percebeu)

Deixa eu adivinhar. Você tá com um projeto Laravel rodando, tem uns 5, 10, talvez 15 formulários que recebem CPF. Cadastro de cliente, cadastro de fornecedor, atualização de perfil, checkout, área administrativa… e em cada um desses lugares tem aquela mesma lógica de validação de CPF. Copiada. Colada. Com pequenas variações. E tá tudo bem. Até o dia em que o cliente pede pra mudar uma regra. Ou um bug aparece em um formulário e funciona normal no outro. Aí você abre o projeto, dá um Ctrl+Shift+F procurando "cpf" e… surpresa: tem oito lugares diferentes com a mesma validação. Com mensagens de erro escritas de oito jeitos. Uma delas até com erro de digitação. Já passou por isso? Então senta que essa conversa é pra você. O crime acontecendo em câmera lenta Olha esse cenário aqui, que eu garanto que você já viu (ou escreveu): // app/Http/Requests/StoreClienteRequest.php public function rules () { return [ 'cpf' => [ 'required' , function ( $attribute , $value , $fail ) { $cpf = preg_replace ( '/[^0-9]/' , '' , $value ); if ( strlen ( $cpf ) !== 11 ) { $fail ( 'CPF inválido.' ); return ; } // ... mais 20 linhas do algoritmo }], ]; } E aí, três dias depois, no outro Form Request: // app/Http/Requests/StoreFornecedorRequest.php public function rules () { return [ 'cpf' => [ 'required' , function ( $attribute , $value , $fail ) { $cpf = preg_replace ( '/[^0-9]/' , '' , $value ); if ( strlen ( $cpf ) !== 11 ) { $fail ( 'O CPF informado não é válido!' ); // mensagem diferente, claro return ; } // ... mais 20 linhas quase iguais, mas não exatamente }], ]; } Multiplica isso por 8 telas. Agora imagina o seu "eu do futuro" tentando manter isso. Dá pra sentir a dor daqui. DRY: a sigla que vai salvar seu projeto (e sua sanidade) DRY significa Don't Repeat Yourself . Em bom português: não se repita, caramba. A ideia é simples: cada pedaço de conhecimento (uma regra de negócio, um cálculo, uma validação) deve existir em um único lugar no seu sistema. Se precisar mudar, você muda em u

2026-06-26 原文 →
AI 资讯

Laravel API Development in Morocco: Architecture Guide 2026

Laravel API Development in Morocco: Architecture Guide 2026 Laravel remains the #1 PHP framework for API development in 2026 Laravel remains the #1 PHP framework for API development in 2026, and Morocco has become a hub for quality Laravel freelancers and teams. Here is the complete guide to building production-grade APIs with Laravel, based on 40+ projects shipped. Why Laravel for APIs in 2026 Eloquent ORM — most expressive DB layer in any framework Sanctum for SPA/mobile auth (simpler than Passport for most cases) Scout for Meilisearch / Algolia / Elastic full-text search Queues with Horizon for background jobs Octane for performance (Swoole / RoadRunner) Deep ecosystem : Telescope, Pulse, Forge, Vapor REST vs GraphQL — What to Choose Criteria REST GraphQL Learning curve Low Medium-high Caching Easy (HTTP) Complex Over-fetching Common Solved Mobile bandwidth Higher Optimized Best for Public APIs, simple CRUD Complex dashboards, mobile apps My default : REST with Laravel API Resources unless the client has clear GraphQL-specific needs (mobile app with variable fields, highly nested data). Standard Laravel API Architecture app/ ├── Http/ │ ├── Controllers/Api/V1/ │ ├── Requests/ (FormRequest for validation) │ └── Resources/ (API Resources for shaping output) ├── Models/ ├── Services/ (business logic) ├── Repositories/ (optional, if complex queries) ├── Jobs/ └── Events/ Key architectural decisions Versioning via URL (/api/v1/users) not headers — simpler FormRequest for validation (never validate in controller) API Resources for every response (shape, transforms, conditionals) Services layer when controllers exceed 100 lines Dedicated DTOs for complex payloads (spatie/laravel-data) Authentication — Sanctum Setup SPA on same domain : cookie-based, CSRF protected Mobile app / 3rd party : personal access tokens Revocation endpoint for logout Token abilities for granular permissions Rate Limiting & Security RateLimiter facade — per user, per IP, per endpoint CORS : use c

2026-06-26 原文 →
AI 资讯

Creating Short Links with PHP: A Practical Guide

Creating Short Links with PHP: A Practical Guide URL shorteners are everywhere. They're used in marketing campaigns, email newsletters, QR codes, social media posts, affiliate links, and analytics platforms. While most developers are familiar with services like Bitly, integrating a URL shortener directly into your application is often much more useful. In this article, we'll build short links from PHP using an API. Why Create Short Links Programmatically? Creating links through a dashboard works for occasional usage. But applications often need to generate links automatically. Common examples include: Email campaigns User invitations Affiliate systems QR code generation Marketing automation Analytics tracking Customer portals An API allows applications to create and manage links without human interaction. The Traditional HTTP Approach Most URL shortener APIs work through simple HTTP requests. For example: $client = new GuzzleHttp\Client (); $response = $client -> post ( 'https://example.com/api/links' , [ 'headers' => [ 'X-Api-Key' => $apiKey , 'Content-Type' => 'application/json' , ], 'json' => [ 'url' => 'https://example.com/article' ] ] ); $data = json_decode ( $response -> getBody (), true ); echo $data [ 'short_url' ]; This works. But once your application creates dozens or hundreds of links, the amount of boilerplate code starts growing. Using a PHP SDK A PHP SDK removes most of the repetitive work. Installation is usually straightforward: composer require lix-url/php-sdk Creating a link becomes much simpler: $link = $client -> links () -> create ([ 'url' => 'https://example.com/article' ]); echo $link -> shortUrl ; The SDK handles: Authentication HTTP requests Response parsing Error handling DTO mapping This allows your application code to remain clean. Creating Your First Short Link Let's imagine an application that sends invitation emails. $inviteLink = $client -> links () -> create ([ 'url' => 'https://myapp.com/invite/abc123' ]); echo $inviteLink -> short

2026-06-26 原文 →