AI 资讯
Keeping Doctrine Entities Honest with DTOs and ObjectMapper
Originally posted on https://symfonycasts.com/blog/honest-entities Your Doctrine entities are lying to you! For years, the standard way to build Doctrine entities in Symfony has looked something like this (and it's still what MakerBundle generates today): #[ORM\Entity] class ConferenceTalk { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null ; #[Assert\NotBlank] #[ORM\Column(length: 255)] private ?string $title = null ; #[ORM\Column(type: Types::TEXT, nullable: true)] private ?string $abstract = null ; public function getId (): ?int { return $this -> id ; } public function getTitle (): ?string { return $this -> title ; } public function setTitle ( ?string $title ): static { $this -> title = $title ; return $this ; } public function getAbstract (): ?string { return $this -> abstract ; } public function setAbstract ( ?string $abstract ): static { $this -> abstract = $abstract ; return $this ; } } At first glance, this looks perfectly reasonable. The title field is required. We know that because it has a NotBlank constraint and the database column is not nullable. But look closer. private ?string $title = null ; public function setTitle ( ?string $title ): static public function getTitle (): ?string According to the PHP type system, the title is optional. In fact, the public API of this class explicitly allows us to set it to null . That means this is perfectly valid: $talk = new ConferenceTalk (); And so is this: $talk = new ConferenceTalk (); $talk -> setTitle ( null ); Both objects represent a conference talk that can never be successfully persisted. Eventually, Doctrine catches the problem: $talk = new ConferenceTalk (); $entityManager -> persist ( $talk ); $entityManager -> flush (); // boom! SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null The database knows that a conference talk must have a title. Our PHP code does not. So why do we build entities this way? Historically, this pattern was optimized for simpli
AI 资讯
Giving an AI agent the keys without giving it the building: RBAC + org-scoped MCP tools in Laravel
Exposing your app to an AI agent over MCP is basically handing someone a master keyring and trusting them to only open the doors they're supposed to. That trust is a bug waiting to happen. This week I wired up a batch of MCP tools over a multi-tenant Laravel app, and the whole exercise was really about one question: how do I let an agent drive the app without letting it drive someone else's data? Here's the thing about MCP tools — each one is an endpoint. An agent calls list_events , publish_event , check_in_participant , and your server runs code on the caller's behalf. The moment you have more than one tenant, every single tool needs to answer two questions before it does anything: are you allowed to do this , and are you allowed to do it *here *. Authorization and scope. Skip either and you've built a confused deputy. The trap: ambient scope doesn't exist under token auth In a normal web request, multi-tenancy is comfortable. You've got a logged-in user, a global scope on the model that quietly appends where organization_id = ? , and you mostly forget it's there. Everything Just Works because there's an ambient "current organization" sitting in the session. MCP tools don't have that. The caller authenticates with a token, there's no session, no middleware stack that set up a current-tenant context. If you lean on a global OrganizationScope that reads "the current org" from somewhere, it reads nothing — and a query you assumed was fenced returns every tenant's rows. That's the kind of bug that doesn't throw an error; it just silently leaks. So the rule I settled on: under token auth, never rely on ambient scope. Filter explicitly, every time, in one place. That "one place" is a small trait every event-scoped tool pulls in: trait ResolvesOrgEvents { protected function resolveOrgEvent ( Authenticatable $user , string $uuid ): ?Event { if ( empty ( $user -> organization_id )) { return null ; } return Event :: query () -> withOrganization ( $user -> organization_id )
AI 资讯
Omnia Ipsum: Unified placeholder content for Symfony
Rethinking fake content in Symfony projects A prototype web page displaying pure placeholder content When building early UI prototypes or shaping design systems in Symfony, placeholder content becomes a constant companion. Lorem ipsum text. Dummy profile photos. Placeholder videos. Silent audio. Temporary avatars. Realistic fake user data. Every project needs them — and yet most setups rely on a patchwork of libraries, links and hardcoded values. Omnia Ipsum aims to fix that by giving Symfony developers a single, elegant toolkit for placeholder content of all kinds. In this article, I will walk you through the motivation behind the project, the conceptual patterns it follows, and its most advanced features — all designed to make your prototyping workflow faster, cleaner and more maintainable. Motivation: Why a placeholder library? Most Symfony projects start the same way: You add lorem ipsum text manually into Twig templates. You grab placeholder images from an external service. You generate avatars using yet another site. You paste in temporary YouTube or stock video URLs. You install Faker separately whenever realistic data is needed. The result is inconsistent, fragmented and difficult to maintain. And even worse: placeholder content often leaks into production unless guarded carefully. The idea behind Omnia Ipsum was simple: “If your UI needs placeholder content, it should come from one place — predictable, configurable, and accessible directly from Twig.” This cuts down on boilerplate, cognitive overhead, and the "temporary chaos" of early-stage templates. Quick Start Prerequisite Go to github.com/symfinity/recipes and follow the instructions to add the required recipe repository. Installation composer require --dev symfinity/omnia-ipsum Usage Use the Twig functions immediately: <img src= " {{ omnia_image ( 600 , 400 ) }} " alt= "Placeholder" > <img src= " {{ omnia_avatar ( 'John Doe' , 100 ) }} " alt= "Avatar" > <video src= " {{ omnia_video ( 1920 , 1080 ) }}
AI 资讯
Font Manager: Multi-format Font export for Symfony
The Problem Typography should be one of the simplest parts of a project. In reality, it often ends up scattered across multiple layers: Bootstrap: $font-family-base variables Tailwind: JavaScript configuration TypeScript: type definitions Design systems: W3C Design Tokens The same font information gets copied and maintained in several places. Every update means touching multiple files, hoping everything stays in sync. It's repetitive, error-prone, and easy to get wrong. So I built Font Manager. Define your fonts once and export them in whatever format your project needs — CSS, Bootstrap variables, Tailwind configuration, TypeScript definitions, design tokens, and more. The Solution A simple Twig function: {{ font_manager ( 'Ubuntu' , '400 700' ) }} Configuration: symfinity_font_manager : export : formats : - scss_bootstrap - tailwind_config - typescript_definitions One lock command: php bin/console fonts:lock Every format, automatically generated. Perfectly synced. Bootstrap Example Before: // Manually copy font name $font-family-base : 'Ubuntu' , sans-serif ; // ❌ Duplication @import 'bootstrap/scss/bootstrap' ; After: symfinity_font_manager : export : formats : [ scss_bootstrap ] php bin/console fonts:lock // app.scss @import './assets/styles/fonts-bootstrap' ; // ← Auto-generated @import 'bootstrap/scss/bootstrap' ; Bootstrap uses your fonts automatically. No manual mapping. No duplication. Tailwind Example symfinity_font_manager : export : formats : [ tailwind_config ] // tailwind.config.js const fonts = require ( ' ./assets/fonts-tailwind.config.js ' ); // ← Auto-generated module . exports = { theme : { extend : { fontFamily : fonts . fontFamily } } }; <p class= "font-sans" > Your custom font, via Tailwind. </p> TypeScript Example symfinity_font_manager : export : formats : [ typescript_definitions ] import { fonts , type FontFamily } from ' ./assets/fonts ' ; applyFont ( element , ' sans ' ); // ✓ Valid applyFont ( element , ' invalid ' ); // ✗ TypeScript erro
AI 资讯
Playwright versus WordPress's "admin email confirmation" screen — how automation can clear the 6-month gate
If you drive the WordPress admin via Playwright for long enough, one day a screen you've never seen before will appear after login , and everything downstream stops working. Is admin@example.com still the correct admin email address? [ Yes, the email is correct ] [ Change the address ] That's WordPress's admin email confirmation screen . Roughly every six months, after the admin user logs in, this confirmation screen gets injected — standard behavior since WP 4.9. A human just clicks once. An automation script can't see it without explicit handling. Why automation gets stuck A straightforward Playwright login looks like: page . fill ( ' #user_login ' , user ) page . fill ( ' #user_pass ' , pwd ) page . click ( ' input[type= " submit " ] ' ) page . wait_for_load_state ( ' domcontentloaded ' ) # Assumes we're on the dashboard page . goto ( ' /wp-admin/plugins.php ' ) But on a "confirmation day," the URL right after wait_for_load_state is something like /wp-admin/profile.php?...action=confirm_admin_email... — the confirmation screen. You thought you were navigating to the plugins page, but the DOM you expected isn't there. Subsequent selectors fail, and everything downstream cascades into failure. A specific selector identifies the screen WordPress's confirmation screen has a uniquely-named submit button: <input type= "submit" name= "correct-admin-email" value= "Yes, the email is correct" /> If input[name="correct-admin-email"] exists on the page, you're on the confirmation screen. The same selector serves as both the detection signal and the click target , so handling is only a few lines: admin_email_confirm = page . locator ( ' input[type= " submit " ][name= " correct-admin-email " ] ' ) if admin_email_confirm . count () > 0 : logger . info ( " Confirmation screen detected — clicking ' email is correct '" ) admin_email_confirm . first . click () page . wait_for_load_state ( ' domcontentloaded ' , timeout = 30000 ) Insert this after the post-login wait_for_load_state
AI 资讯
The Polling API Is the Most Underrated RFC PHP Has Shipped in Years
While most of the community spent the spring arguing about generics, a different RFC slipped into PHP 8.6 with almost none of the attention it deserved. No long Twitter threads. No blog posts dissecting the implications. Just a quiet vote that closed on the third of June with 33 in favour, one against, and four abstaining, from a list of names that includes the Composer author, the FrankenPHP creator, and a healthy chunk of the people who actually maintain the async libraries you depend on. That RFC is the Polling API, authored by Jakub Zelenka as part of his ongoing stream evolution work. I want to make the case that it is the most consequential thing to land in PHP in years, and that the reason nobody is talking about it is exactly the reason it matters. The problem you have been quietly working around If you have ever written anything that needs to watch more than one socket at a time, you have met stream_select() . It is the only I/O multiplexing primitive PHP has shipped for most of its life, and it is built on the select() system call from 1983. It works. It also carries a set of limitations that every async library author has had to engineer around. The first is the file descriptor ceiling. The current implementation caps out at around 1024 descriptors on most systems, which is fine until the moment it very much is not. The second is the complexity. select() is O(n): it scans every descriptor you hand it on every single call, so performance degrades as you add connections. The third is that it gives you no access to the mechanisms the rest of the world has been using for two decades. There is no epoll on Linux, no kqueue on BSD or macOS, no event ports on Solaris. There is no edge-triggered mode and no one-shot mode. This is why every serious async runtime reaches past select() . Node, Nginx, Go's net package, Rust's Tokio: they all sit on epoll or kqueue, because that is the foundation high-concurrency networking is built on. PHP was the last major runtime w
AI 资讯
Dev Log: 2026-06-23 — Query Cleanups, Real Health Checks, Safer MCP Tools, and Password-Reset Plumbing
A wide day rather than a deep one — four separate threads across a few projects, each with a lesson worth keeping. I'll teach the patterns and keep the specifics generic. The through-line: make the system honest about what it's actually doing — which queries it fires, whether a service is really up, what a tool will do when you call it twice, and in what order a password change should land. The performance thread got big enough that I split it into its own focused post; here's the short version plus the three other threads. Thread 1 — Stop paying for queries you don't use A sustained sweep through an app (and the package behind it) hunting wasted database work. The highlights: Arm an N+1 detector in dev only. A query detector wired in behind an environment check turns invisible lazy-loads into a visible to-do list. Never in production — it's a developer aid, not a runtime guard. Unused eager loads are N+1s in disguise. Index screens love to with(['creator', 'approver']) for columns a redesign later removed. Not a loop, but the same disease: queries you hydrate and throw away. Delete the eager loads with no consumer in the view. Memoize per-request constants. A default-connection resolver and a sidebar unread count were both recomputed on every call. ??= once, reuse for the rest of the request. Collapse a dashboard's stat queries. ~20 count() calls became one grouped query per table, wrapped in a short-lived cache. A dashboard can tolerate being a few seconds stale; trade live-to-the-second for cheap. The meta-lesson: performance at this layer is mostly removal , and you lock it in with a Pest query-count assertion so nobody quietly re-adds an N+1 six months later. Full write-up in the focused post. Thread 2 — Health checks that actually check Here's a trap I keep seeing in "is it up?" tooling: the check verifies the record exists, or that a config row is present, and calls it green. That's not a health check — that's a config check. The service can be configured per
AI 资讯
A Day of Performance Hardening: Hunting N+1s and Killing Wasted Queries in Laravel
Performance work has a reputation for being glamorous — the heroic "we cut latency by 80%" story. Most days it's not that. Most days it's a janitorial pass: you go looking for the queries you're firing without realizing it, and you quietly delete them. That was today. One sustained sweep across an app and the package that backs it, chasing the same theme everywhere: stop asking the database for things you don't use. Let me walk through the patterns, because they generalize to any Laravel app of a certain age. First, make the invisible visible You can't fix N+1s you can't see. The first move was wiring up an N+1 detector in the local/dev environment only — beyondcode/laravel-query-detector . It hooks into the request lifecycle, watches your Eloquent relationship loads, and screams (in the console, or as an exception if you want it strict) when it spots the classic loop-and-lazy-load pattern. The "dev-only" part matters. You never want a query detector running in production — it adds overhead and it's a developer aid, not a runtime guard. So it goes in behind an environment check, registered only when the app isn't in production: public function register (): void { if ( $this -> app -> environment ( 'local' , 'testing' )) { $this -> app -> register ( \BeyondCode\QueryDetector\QueryDetectorServiceProvider :: class ); } } Think of it like a smoke detector you only arm while you're cooking. It's noisy by design — that's the point. The noise is a to-do list. Eager loads you don't actually use are just N+1s wearing a disguise Here's the counterintuitive one. We're all trained to fix N+1s by adding with() . But the opposite bug is just as common and almost never gets caught: you eager-load a relationship, and then... never touch it in the view. Index screens are the worst offenders. Someone builds a listing, eager-loads creator and approver so the table can show names, then a redesign drops those columns — but the with(['creator', 'approver']) stays. Now every page load hyd
AI 资讯
When WP admin shows a plugin update but WP-CLI doesn't — making automation see proprietary updaters
You open the "Updates" page in WordPress admin and see that Elementor Pro / ACF Pro / vk-blocks-pro have updates available. Then you run wp plugin update --all from your automation, and those exact plugins don't update. The asymmetry — "the admin sees it; WP-CLI doesn't" — traces back to how WordPress detects updates and how premium plugins layer proprietary update mechanisms on top of that. Here's the mechanism and how an automation tool can adapt. WordPress update detection is held by a transient cache WordPress doesn't decide "is there an update?" on every request. It caches the answer in the wp_options table as a transient, valid for up to 12 hours. The key entries: _site_transient_update_plugins — latest plugin versions _site_transient_update_themes — themes _site_transient_update_core — core If those transients are stale, even a version that just shipped on wordpress.org reads as "no update needed." WP-CLI consults the same transients, so stale cache = WP-CLI misses the update too . In one customer environment on ConoHa WING, we reproduced "version X is on wordpress.org, WP-CLI doesn't see it" directly. Trap 1 and fix 1 — force-refresh the transients before listing updates The first step was simple: at the start of a maintenance run, delete the three transients before querying the update list . def _flush_update_transients ( self , conn , wp_cmd , wp_path , site_name ): """ Delete update transients between DB backup and update step """ for t in ( " update_plugins " , " update_themes " , " update_core " ): conn . run ( f " { wp_cmd } transient delete { t } --path= { wp_path } " , warn = True , hide = True , ) Deleting the transients triggers a rebuild on the next wp plugin list --update=available . During the rebuild, WordPress reaches out to wordpress.org, so the returned list reflects the current release state . That handled the "we were just reading a stale cache" cases. But it didn't help with premium plugins. Trap 2 — with --skip-plugins , Pro updater filt
AI 资讯
NVIDIA peermem invalid argument-fix
nvidia-peermem "Invalid argument" on Ubuntu — Fix GPUDirect RDMA with DMA-BUF TL;DR: If modprobe nvidia-peermem fails with Invalid argument ( -EINVAL ) on a system using the inbox Ubuntu InfiniBand stack ( rdma-core ), the module is not broken and you do not need it. nvidia-peermem requires an API that only exists in MLNX_OFED. On Hopper/Blackwell GPUs with the NVIDIA open driver, use DMA-BUF instead — it does GPUDirect RDMA natively. The one gotcha: you must enable nvidia-drm modeset=1 . Applies to: Ubuntu 22.04 / 24.04, inbox rdma-core stack, NVIDIA open kernel driver, H100 / H200 / B200, ConnectX-6/7 (or any HCA with ODP support). The symptom $ sudo modprobe nvidia-peermem modprobe: ERROR: could not insert 'nvidia_peermem' : Invalid argument dmesg shows nvidia-peermem loaded but registered nothing, or the load returns -EINVAL . GPUDirect RDMA appears to be unavailable. Why this happens (and why it is not a bug) nvidia-peermem is the legacy path for GPUDirect RDMA. It registers GPU memory with the InfiniBand subsystem through a Mellanox-proprietary kernel API: ib_register_peer_memory_client () That symbol only exists in MLNX_OFED's build of ib_core . It is not in the mainline kernel, and it is not in rdma-core , which is the inbox InfiniBand stack on Ubuntu. If you are on the inbox stack, nvidia-peermem was compiled without that API present, so it can never bind and always returns Invalid argument . No module parameter or config change will fix it, because the thing it needs was never there. Do not install MLNX_OFED just to make nvidia-peermem load. That works, but it is the wrong fix — you would be adding a heavy proprietary stack to revive an obsolete module. There is a native path already in your kernel. The fix: use DMA-BUF On Hopper and newer with the open driver, GPUDirect RDMA works through DMA-BUF , a mainline Linux framework. No external module, no MLNX_OFED. Requirements (check these first) NVIDIA open kernel driver (not the proprietary build) nvidia-drm
开发者
bcrypt and Laravel: 72 Bytes, Not 72 Characters
I expected bcrypt to silently drop characters past 72. I did not expect it to bake in half an emoji. That's what happens with a specific password combination I tested. The original password still works. But strip the emoji (a password manager, a different keyboard, a Unicode normalizer) and you're locked out. Your Laravel validator passed it as valid the whole time. The 72-Byte Rule bcrypt has a hard input limit of 72 bytes. Not characters - bytes. When you call password_hash($password, PASSWORD_BCRYPT) , PHP silently truncates anything past byte 72. Most developers know this in theory. But for ASCII-only apps, it never bites. 72 ASCII characters is already a very long password, and the silent clip is harmless in practice. The trouble starts with multi-byte scripts. How Many Characters Fit? Character set Bytes per char Effective bcrypt limit ASCII 1 72 chars Cyrillic 2 36 chars CJK (Chinese, Japanese, Korean, common block) 3 24 chars Emoji 4 18 chars Past the byte limit, a longer password adds no security at all. A 200-character Cyrillic password hashes identically to its own first 36 characters. Byte 73 and beyond simply do not exist from bcrypt's point of view. So "longer always produces a stronger bcrypt hash" is not true. A Cyrillic user with a 37-character password gets silently truncated at char 36. The hash is still consistent. The user logs in fine, but any variation past character 36 doesn't matter to bcrypt. Annoying from a security standpoint, but it does not break login. The Split-Byte Trap The 72-byte limit cuts at a byte boundary, not a character boundary. If a multi-byte character falls on that cut, bcrypt bakes in an incomplete UTF-8 sequence. // 35 Cyrillic chars = 70 bytes, emoji = 4 bytes, total = 74 bytes $password = str_repeat ( 'А' , 35 ) . '🔑' ; $hash = password_hash ( $password , PASSWORD_BCRYPT ); password_verify ( $password , $hash ); // ? password_verify ( str_repeat ( 'А' , 35 ), $hash ); // ? password_verify ( str_repeat ( 'А' , 36 ), $h
开发者
The 200-byte trap: why WordPress core updates break Arabic URLs
You update WordPress on a quiet afternoon — a routine release, the kind you've installed a hundred times. The dashboard says everything went fine. Then the 404s start: not a handful, but every long-headlined article in your archive, all at once, all in Arabic. Nothing in the update log mentions it. No plugin changed. And the cruel part: the data that made those URLs work is already gone — shaved off inside a database-upgrade routine that ran for a few milliseconds and reported success. This isn't a freak accident or a broken plugin. It's three separate assumptions baked into WordPress core, each hard-coding the same number — 200 — and Arabic sites are almost uniquely exposed to all three. We hit this running WordPress for Arabic newsrooms, the same high-traffic publishing we've written about surviving breaking-news spikes . We traced it to the exact lines in core and built a fix that survives every future update. Here's the whole story. Why Arabic URLs hit a wall English never does WordPress stores a post's slug in the post_name column of wp_posts , and a category or tag slug in the slug column of wp_terms . Both are VARCHAR(200) by default — room for 200 characters, which for an English headline is generous. "Everything you need to know about our new pricing" is barely fifty. You'd have to write a paragraph to run out. Arabic is a different arithmetic, because of what WordPress actually stores in that column. It doesn't keep the raw Arabic text — it stores the percent-encoded form, the same %XX sequence that travels in the URL. Take a single word: الذكاء → %d8%a7%d9%84%d8%b0%d9%83%d8%a7%d8%a1 Every Arabic letter is two bytes in UTF-8, and every byte becomes a three-character %XX token. So one Arabic character costs about six characters of column space. Do the division: VARCHAR(200) holds roughly 33 Arabic characters. A normal news headline — "القبض على المتهمين في قضية الاحتيال الإلكتروني" — blows past that before it's halfway done. So Arabic publishers learn early
开发者
Toggle navigation not working on ios, android en windows perfect
I need your help. I've problems with an Navigation button on ios. On Windows in all browsers it's working good but on an ios device the menu isnt opening. I've tried to run devtools on an ios device to take a look in the console but this stays empty. https://rb.gy/7o5yql This is the url of the website. I've tried to remove the country flag and the logo i thought it was in the way of the button but nothing helps. Who would like to take a look at it?
AI 资讯
Pinion: Resumable File Uploads for PHP
(Without Fighting upload_max_filesize ) You deploy your app. A user picks a 400 MB video. They hit upload. The progress bar freezes. Then — nothing. You check the logs. POST Content-Length exceeded post_max_size . Again. We've all been there. The fix is usually "raise PHP limits" or "use S3." Both work — until you're on shared hosting, a legacy VPS, or a client who won't touch php.ini . That's the problem Pinion solves. What is Pinion? Pinion is an open-source resumable chunked upload protocol for PHP. Instead of one giant multipart/form-data request, the browser sends the file in small parts (default: 5 MB). The server stores each part, then assembles the final file on disk. Three steps. That's the whole contract: init → upload parts → complete Package Registry Role pinoox/pinion Packagist PHP server engine @pinooxhq/pinion-client npm Browser client Protocol id: pinion · version: 2 Why not just use S3? Object storage is great. But sometimes you need files on your server : A CMS media library on local disk A Laravel app without cloud budget Shared hosting with no S3 SDK An admin panel behind a simple PHP API Pinion isn't a CDN or a storage service. It's a protocol — a stable HTTP contract that works in plain PHP, Laravel, or Pinoox. How it works (30-second version) sequenceDiagram participant Browser participant API participant Disk Browser->>API: POST /init (filename, size, fingerprint) API-->>Browser: upload_id, chunk_size, missing_indexes loop Each part Browser->>API: POST /upload (chunk + SHA-256 hash) API->>Disk: store part end Browser->>API: POST /complete API->>Disk: assemble file API-->>Browser: done ✓ Resume is built in. The client sends a fingerprint ( name:size:lastModified:type ). If the connection drops, the same file picks up where it left off — only missing parts are re-uploaded. Integrity too. Each part gets a SHA-256 chunk_hash . The server can reject corrupted chunks before they pollute your disk. Server side: 10 lines of PHP composer require pinoo
AI 资讯
How to Build a WordPress Plugin Licensing System from Scratch (Without Freemius)
If you're shipping a commercial WordPress plugin, sooner or later you'll need a licensing system. Something that lets paying customers activate the plugin on their site, locks it to that domain, and stops people from sharing the same key across fifty sites. The default answer in the WordPress world is Freemius or EDD Software Licensing. They're great. They're also a revenue share, a third-party dependency, and a black box you don't control. When we built RideCab WP , a commercial WooCommerce taxi booking plugin, we decided to build our own. Here's the architecture, the code, and the gotchas we hit along the way. What a Licensing System Actually Needs to Do Before writing any code, get clear on the requirements. A real plugin licensing system needs to: Generate unique license keys when someone buys Let the customer activate the key on their site Bind that key to one (or N) domains Validate the key periodically so revoked or expired keys stop working Handle deactivation when a customer moves to a new domain Fail gracefully — never lock a paying customer out because your license server hiccuped Optionally: deliver plugin updates only to valid license holders We'll cover 1 through 6 in this post. Update delivery is a separate beast and I'll write it up next. The Architecture The system has two halves that live in two different places. The license server runs on your own infrastructure — for us, it's a WordPress must-use plugin (mu-plugin) on the same WordPress install that powers our marketing site. It: Stores license keys in a custom database table Exposes a small REST API for activate, deactivate, and validate calls Provides an admin dashboard to view, create, and revoke keys The client is a PHP class shipped inside the commercial plugin (RideCab WP, in our case). It: Adds a license settings page to the plugin Calls home on activation Caches the validation result Re-validates quietly in the background Two pieces, talking over HTTPS, with the customer's domain as the b
AI 资讯
The Tips Behind API Artisan: Building Laravel APIs Developers Actually Want to Use
I have just finished writing API Artisan: A Guide to Building APIs with Laravel , and I am giving it away for free. Before you commit to 300-odd pages, let me give you the short version: the tips, patterns, and small decisions that separate an API that technically works from one that developers are genuinely happy to depend on. None of this needs more hardware, a different framework, or a bigger team. It needs you to point your attention at the right things. These are the ones I keep coming back to. Start by measuring the right thing Ask most teams how they know their API is good and you get a single question back: does it work? Can I hit this endpoint and get a response? That question is necessary, and it is nowhere near enough. The question I want you to ask instead is whether your API is liveable with. Can a developer read your docs, understand your auth model, make a successful request, and handle an error without contacting support, trawling a forum, or guessing what a status code is trying to tell them? The gap between "works" and "liveable with" never shows up in a sprint retro, but it shows up everywhere else: in support volume, in integration timelines that overrun, and in the quiet moment a developer decides to build around your API rather than with it. Everything else in the book hangs off one mindset shift: an API is a product. It has users. Treat it as an implementation detail and it will behave like one. It will change without warning when your internals change, and it will be inconsistent because different people wrote different parts on different days with different conventions. Write the contract before the code The natural way to build an endpoint is to write the handler, return some data, and document it afterwards if there is time. It feels efficient, and in the short term it is. The problem is what it produces: a contract that was never designed, only discovered. Let me show you the trap, because I have watched it catch good developers. You have
开发者
Building Lightweight PHP Microservices with webrium/core — No Framework Bloat Required
Do you really need a full framework to handle a few API endpoints or webhooks? Laravel and Symfony are excellent tools — for large applications. But when you're building a focused microservice, a webhook receiver, or a lightweight REST API, bootstrapping a full-stack framework means carrying hundreds of files, a massive autoloader, and a dependency tree you'll never fully use. That's the problem webrium/core was built to solve: a minimalist, zero-dependency PHP micro-framework written entirely from scratch, designed to stay out of your way. Installation composer require webrium/core That's it. No configuration files to publish, no service providers to register. The Entry Point Every webrium application starts with the same three lines: <?php require_once __DIR__ . '/vendor/autoload.php' ; use Webrium\App ; use Webrium\Route ; App :: initialize ( __DIR__ ); // ... your routes here App :: run (); App::initialize() sets the root path and loads the global helper functions. App::run() initializes error handling and dispatches the current request through the router. Routing The router supports all standard HTTP methods. Route handlers can be closures, a Controller@method string, or an [Controller::class, 'method'] array. Basic routes: Route :: get ( '/status' , fn () => [ 'status' => 'alive' ]); Route :: post ( '/items' , fn () => [ 'created' => true ]); Route :: put ( '/items/{id}' , fn ( $id ) => [ 'updated' => $id ]); Route :: patch ( '/items/{id}' , fn ( $id ) => [ 'patched' => $id ]); Route :: delete ( '/items/{id}' , fn ( $id ) => [ 'deleted' => $id ]); Route handlers return an array — the framework automatically encodes it as JSON and sends the correct Content-Type header. Dynamic parameters: Route :: get ( '/users/{id}/posts/{postId}' , function ( $id , $postId ) { return [ 'user_id' => $id , 'post_id' => $postId , ]; }); Named routes: Route :: get ( '/users/{id}' , fn ( $id ) => [ 'id' => $id ]) -> name ( 'users.show' ); // Generate the URL elsewhere: $url = rout
AI 资讯
Turn any PHP host into a gateway to your local network with host2gateway
Ever wanted to turn a simple PHP host into a gateway for your local network? I built host2gateway to do exactly that. ProfiDE / host2gateway Uses a PHP host or web server to create a gateway that securely allows access to clients through it. host2gateway host2gateway is a tool designed to provide access from a web server (Gateway) to a client without requiring static IP addresses, port forwarding, changing firewall rules, or other complex configurations . It is written in PHP and can be deployed on most hosting provider environments. Features No need for static IP or port forwarding: There is no requirement to modify your firewall or router settings. Platform-independent: Works anywhere PHP 8.2 or higher is supported, making it suitable for most shared hosting services. Lightweight and simple: Minimal dependencies and easy deployment. Strong encryption built-in: Uses a powerful encryption mechanism that secures all communication, even if SSL/TLS is not available on the hosting provider. Your data is protected at all times, regardless of your environment. How It Works The client establishes an outbound connection to a Gateway server that is accessible from the internet (a PHP-enabled web host). Both sides communicate… View on GitHub 🔥 What is host2gateway? It's a lightweight tool that transforms any server running PHP into a gateway that can route traffic, manage requests, and act as a bridge between your local network and external services. No heavy dependencies. No complex configs. Just PHP, Cron and a network interface. 🧠 Why I built this Most gateway solutions are bulky, written in Go or Rust, and require root access and system-level changes. But what if you only have: A shared hosting account A basic VPS with PHP enabled A Raspberry Pi running a PHP server host2gateway fills that gap. It gives you gateway-like capabilities using the tools you already have. 🛡️ Use cases Use Case Description Local network bridge Connect isolated parts of your network Traffic inspe
AI 资讯
How a Five Line Architecture Test Caught a Data Leak a Code Review Missed
TL;DR: Pest PHP can test the structure of your code, not just its behavior. Write your team rules as architecture tests and CI enforces them on every commit. One such test caught a multi-tenant data leak that a human review had missed. We had a rule. Every model holding tenant-specific data must use our BelongsToTenant trait. That trait adds the global scope that keeps one clinic from seeing another clinic's data. The rule was in onboarding. It was in the code review checklist. Everyone knew it. A developer joined the team. Three weeks in they added a new model and forgot the trait. The reviewer was focused on the business logic, which was genuinely well written, and did not notice the missing trait. The model shipped. For two days one clinic could see fragments of another clinic's data in one specific report. A support ticket caught it. Our tests did not. That was the day architecture tests went into the project. What an Architecture Test Is Most tests check behavior. Given this input the function returns that output. An architecture test checks structure instead. It asserts things about how the code is organized rather than what it computes. Pest has an arch function for exactly this. // tests/Architecture/ArchTest.php arch ( 'tenant models must use the BelongsToTenant trait' ) -> expect ( 'App\Models' ) -> toUseTrait ( 'App\Traits\BelongsToTenant' ) -> ignoring ( 'App\Models\SystemSetting' ); arch ( 'controllers may not touch the DB facade directly' ) -> expect ( 'App\Http\Controllers' ) -> not -> toUse ( 'Illuminate\Support\Facades\DB' ); arch ( 'services may not depend on the HTTP request' ) -> expect ( 'App\Services' ) -> not -> toUse ( 'Illuminate\Http\Request' ); arch ( 'no env calls outside config files' ) -> expect ( 'App' ) -> not -> toUse ( 'env' ); These run in CI on every commit. Break a rule and the build fails with a message naming the rule and the file that broke it. The Tests That Earned Their Keep The tenant trait test caught four more models over
AI 资讯
Query Objects in PHP: Rich Filtering Without Leaking SQL Into the 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 ship a list endpoint. GET /orders . It returns the customer's orders, newest first. Clean. Then product wants a status filter. Then a date range. Then "only orders over 100 euros". Then pagination. Then sort by total, descending. Six months later the controller signature reads like a tax form, and the repository method that backs it is findByCustomerAndStatusAndMinTotalBetweenDatesOrderedBy(...) with nine parameters, three of them nullable. So you "fix" it. You let the caller pass a Doctrine QueryBuilder into the repository. Or worse: the use case starts assembling WHERE clauses as strings because that was the fastest way to add the next filter on a Friday. Now your application layer knows about table aliases and SQL operators. The domain speaks SQL, and the whole point of having a repository interface is gone. There is a shape that holds: a query object the domain builds, and an adapter that translates it into SQL. The caller describes what it wants in domain terms. The adapter decides how to fetch it. The leak, concretely Here is the version that grows out of control. Every new filter is another nullable parameter. public function search ( ?string $customerId , ?string $status , ?DateTimeImmutable $from , ?DateTimeImmutable $to , ?int $minTotalCents , string $sortBy = 'placedAt' , string $direction = 'DESC' , int $page = 1 , int $perPage = 20 , ): array ; Nine parameters, half of them nullable, two of them ( sortBy , direction ) carrying raw column names that map straight to SQL. Add a filter and the signature grows again. Every caller has to remember positional order. And $sortBy is a column name leaking through the port: t