AI 资讯
A Domain Logger Port: Decoupling From PSR-3 Without Losing Context
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 open a use case that places an order. Near the top of the constructor, alongside the repositories and the payment gateway, sits a Psr\Log\LoggerInterface . The method body calls $this->logger->info(...) three times. It looks harmless. It is the most common way framework concerns leak back into a domain you spent weeks keeping clean. PSR-3 is a fine standard. Monolog is the default implementation in most PHP projects, and it earns that spot. The problem is not the library. The problem is where you point it. When LoggerInterface is a constructor argument in your application layer, your use case now depends on a package whose surface area you do not control, whose log levels you may not want, and whose context conventions are someone else's. The dependency arrow points the wrong way. What PSR-3 drags in Psr\Log\LoggerInterface is eight level methods plus a generic log() . The level taxonomy comes from RFC 5424 syslog: emergency , alert , critical , error , warning , notice , info , debug . That is a system-administration vocabulary. Your domain does not speak it. When a use case calls $this->logger->warning('payment retry') , you have to ask: is a retry a warning or a notice ? The answer is an infrastructure judgment call wearing a domain costume. The method signature also accepts an arbitrary array $context and a string|Stringable $message with {placeholder} interpolation. None of that is something your application code should be deciding. <?php declare ( strict_types = 1 ); namespace App\Application\Order ; use Psr\Log\LoggerInterface ; final readonly class PlaceOrder { public function __construct ( private OrderRepository $ord
AI 资讯
Retries and Circuit Breakers Belong in the Adapter, Not Your Use Case
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 open a use case that places an order. It loads a customer, builds the order, charges a payment gateway, saves, publishes an event. Clean. Then a sprint ago someone added a retry loop around the charge call, because the gateway flaps under load. Now the use case has a for ($i = 0; $i < 3; $i++) , a usleep() , and a comment that says // gateway is flaky on Mondays . The business rule is buried under retry plumbing. A reader who wants to know what placing an order means has to skip past sleep timers and exception counters to find it. Worse, the next person who adds a second outbound call copies the loop. Soon every call to the network has its own hand-rolled retry, each with a slightly different backoff, none of them tested. The use case learned about transient failure. It should never have. Transient failure is not a business rule A use case answers one question: what does the application do when this thing happens? Place an order. Cancel a subscription. Issue a refund. Those are decisions the business cares about. "The payment gateway returned a 503 and we should try again in 200ms" is not a business decision. It is a property of the network between your process and theirs. The domain does not know the gateway is HTTP. It does not know there is a network at all. It asked a port to charge a customer, and the port either succeeds or raises a domain exception. Here is the port, stated in domain language: <?php declare ( strict_types = 1 ); namespace App\Application\Port ; use App\Domain\Customer\CustomerId ; use App\Domain\Shared\Money ; interface PaymentGateway { public function charge ( CustomerId $customerId , Money $amount , s
AI 资讯
Persisting One Aggregate Across Multiple Tables, ORM-Agnostic
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 an Order . It owns line items and a shipping address. In the database that is three tables: orders , order_items , order_addresses . The aggregate is one thing in the domain and three rows-with-children in storage. Now look at what most codebases do with that. The service loads the order, loops the items, saves each one in its own statement. Halfway through, a unique-constraint violation throws. The order header is already committed. Two items are in. One address is missing. You have a row in orders that no part of the system considers valid, and no single place to point at when you ask how it got there. The aggregate is supposed to be a consistency boundary. Saving its parts in separate, independently-committing operations breaks that boundary on the way to disk. This post is about closing it: one repository, one transactional save across every table, and a read path that rebuilds the whole object from rows without leaking the ORM into the domain. The aggregate the domain sees The domain class has no idea it lives in three tables. It holds its children directly and guards their invariants. <?php declare ( strict_types = 1 ); namespace App\Domain\Order ; use App\Domain\Shared\Money ; final class Order { /** @var list<LineItem> */ private array $items ; private function __construct ( private readonly OrderId $id , private readonly CustomerId $customerId , array $items , private Address $shipTo , private OrderStatus $status , ) { if ( $items === []) { throw new InvalidOrder ( 'order needs an item' ); } $this -> items = array_values ( $items ); } public static function place ( OrderId $id , CustomerId $customerId , array $it
AI 资讯
Modeling Money in PHP: Your Own Value Object vs brick/money Behind a Port
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 Open a PHP REPL and type 0.1 + 0.2 . You get 0.30000000000000004 . Now imagine that drift sitting in a total column on an invoice. The bug report does not say "IEEE 754 rounding." It says "the customer was charged one cent too much and finance wants to know why." Money is not a number. It is an amount paired with a currency, and it follows rules a float does not know about. You cannot add 10 USD to 10 EUR. You cannot store 19.99 in a binary fraction and expect it back. You cannot round a third of a cent without deciding how to round it, and that decision belongs to your business, not to your storage engine. This post builds a small Money value object that gets the currency safety right, then shows when to stop hand-rolling and wrap brick/money behind a domain port instead. The point of the port is the same point as every port: the rounding rules live in your domain, and the library stays swappable. Why a float is the wrong type Three separate problems hide inside float $amount . The first is representation. A float is a binary fraction. Decimal amounts like 0.10 have no exact binary form, so they round on every store and load. Sum a few thousand line items and the error compounds into real cents. The second is the missing currency. A bare number cannot tell you whether 1000 means ten dollars or one thousand yen. Two amounts in different currencies are not comparable, but the type system lets you add them anyway. The third is the rounding rule. When you split 10.00 across three line items, you get 3.333... per item. Someone has to decide who absorbs the leftover cent. A float makes that decision silently and inconsistently. The fix
AI 资讯
Hand-Rolled Mappers vs AutoMapper: Keeping the PHP Domain Pure at the Boundary
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 add a column to a table. discount_cents , nullable, default zero. A small migration, a five-minute ticket. The next morning a teammate pings you: orders placed overnight have a discount of null where the domain expected zero, and the total calculation now throws a TypeError deep inside a value object. You trace it back. A reflection-based mapper copied the new column straight onto a property the domain class did not declare, then the next read pulled it back as null and handed it to Money . Nobody wrote the line that connected discount_cents to the domain. The mapper guessed, and the guess leaked the table's shape into a class that was supposed to know nothing about tables. This is the case against automatic mapping at the persistence boundary. A hand-rolled mapper is more typing. It is also the seam that stops the database schema from reaching into your domain. What the boundary is for In a hexagonal layout the domain Order knows about line items, currencies, and the rule that an order needs at least one item. It does not know there is a orders table with a discount_cents column. The repository adapter is the only place those two worlds touch, and the mapper is the translator that stands at that seam. A reflection or annotation-driven mapper collapses the seam. It reads the persistence shape, walks the domain object's properties, and copies whatever names line up. When the two shapes match, it feels free. When they drift, the drift travels silently across the boundary you built it to protect: a renamed column, a new field, a type that does not round-trip. The whole point of the adapter is that the domain and the table can cha
AI 资讯
How a PHP SDK Can Save You Hundreds of Lines of API Integration Code
How a PHP SDK Can Save You Hundreds of Lines of API Integration Code Most APIs provide documentation, examples, and maybe even a Postman collection. That's usually enough to get started. But once your application grows, you'll quickly discover that working directly with HTTP requests introduces a surprising amount of repetitive code. You end up writing the same things over and over: Authentication headers Request serialization Response parsing Error handling Pagination logic DTO mapping This is exactly why SDKs exist. In this article, we'll look at how a PHP SDK can simplify API integrations and reduce maintenance costs over time. The Hidden Cost of Direct API Calls Let's imagine you're integrating a URL shortening API. A typical implementation might look like this: $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' ] ] ); $data = json_decode ( $response -> getBody () -> getContents (), true ); This doesn't seem bad. Now repeat it for: Create link Update link Delete link Get link List links Create group Update group Get profile Eventually your codebase becomes filled with API boilerplate. The business logic becomes harder to see because it's buried under HTTP implementation details. What a Good SDK Does A well-designed SDK abstracts repetitive tasks and exposes a clean programming interface. Instead of dealing with HTTP requests directly, developers work with resources and objects. For example: $link = $client -> links () -> create ([ 'url' => 'https://example.com' ]); This is easier to read and easier to maintain. The SDK becomes responsible for: Authentication Request building Validation Serialization Response mapping Exception handling Consistent Error Handling One common problem with raw API integrations is inconsistent error handling. Without an SDK, every request may need its own validat
AI 资讯
Three gaps the WordPress maintenance industry still hasn't solved — from a survey of four major tools
WordPress maintenance automation has a long-running market, especially outside Japan. ManageWP, MainWP, WP Umbrella, InfiniteWP — each has more than a decade of history behind it. While building our comparison pages, we surveyed all four side by side. An interesting pattern emerged: three things none of the four tools offer . Each is a gap the industry has long treated as "not feasible," and there are structural reasons why. Here's a look at those three unsolved areas — and why they remain unsolved. Gap 1 — Per-plugin updates with HTTP checks between each one In most maintenance tools, plugin updates run in bulk . After the batch, the tool takes a sitewide screenshot diff or HTTP status check, and if anything is broken, "Safe Updates" or "Atomic Updates" features roll everything back at once . Why isn't "one at a time with an HTTP check between each" the standard? The main reason is API design constraints . WordPress's built-in wp_ajax_update-plugin and Worker-plugin APIs (like ManageWP Worker) are designed around batch processing. Doing an HTTP probe from an external host after every single update would add significant per-update overhead. The industry has settled on "bulk update → bulk check" as the natural granularity. The side effect: identifying which plugin caused the breakage often falls to the operator's manual investigation. Gap 2 — Pinpoint rollback (only the one that broke) The industry-standard "Safe Updates" feature is fundamentally a "roll back everything" design. If 20 plugins are batched together and one breaks the site, all 20 updates revert. It's a safety-first choice — but operationally, it means the 19 that finished cleanly are also lost. Why isn't pinpoint rollback (revert only the one that broke) the standard? The root cause is state-management complexity . To pinpoint rollback, you need to keep the pre-update files of each plugin individually. Storage, transfer cost, and dependency consistency checks become impractical over a Worker-plugin HTT
AI 资讯
USPS Just Broke Your Magento Shipping. Here's the Fix.
If your Magento store still depends on the old USPS Web Tools integration, you should assume your shipping rates are either already broken or one change away from breaking. That sounds dramatic, but it is the practical reality we have been seeing. USPS has moved away from the old Web Tools model and toward REST API v3 with OAuth 2.0 authentication. Magento's legacy USPS integration was built for a different era. For merchants, the symptom is simple: rates stop showing up, return inconsistently, or fail under conditions you did not use to worry about. For Magento developers, the reason is also simple: the built-in carrier module is not designed for the current USPS authentication and request model. This article explains what changed, why core Magento falls over here, how to migrate cleanly, and what to watch for whether you choose an extension or a custom build. What changed: USPS Web Tools is not the same platform anymore Historically, Magento's USPS integration talked to Web Tools-style USPS endpoints: structured shipping requests, legacy authentication, and XML responses. That is not the model USPS wants merchants using now. The modern USPS stack is based on: REST API v3 endpoints OAuth 2.0 for authentication Different request and response payloads Different onboarding and credential management patterns That shift matters because it is not just a URL update. It changes authentication, token handling, and request structure. In practical terms, a migration now means: Getting the right USPS developer credentials Exchanging those credentials for OAuth access tokens Updating the carrier request layer to use REST payloads Mapping the new response format back into Magento shipping methods If you skip any of that and try to "patch" the old module with endpoint changes, you are going to waste time. Why Magento 2's built-in USPS module no longer works Magento's built-in USPS module was not architected around OAuth-backed REST API calls. It expects a legacy carrier contract
AI 资讯
Um resumo sobre o padrão de segurança HMAC
Definição O HMAC (Hash-based Message Authentication Code) é um mecanismo de segurança que permite verificar a integridade e autenticidade de uma mensagem, garantindo que ela não foi alterada e que foi gerada por quem possui uma chave secreta. Ele é muito usado em autenticação de APIs, tokens e assinaturas digitais. Analogia Imagine que você envia uma carta dentro de um envelope lacrado com um selo exclusivo que só você e o destinatário conhecem a forma de produzir. Se alguém abrir a carta e alterar qualquer palavra, o selo não vai mais bater com o original. O HMAC funciona exatamente assim: ele “lacra” os dados com uma assinatura impossível de reproduzir sem a chave secreta. Exemplo sem HMAC (inseguro) $payload = [ 'user' => 'joao' , 'exp' => time () + 300 ]; // token simples sem proteção $token = base64_encode ( json_encode ( $payload )); Problema Qualquer pessoa pode: decodificar o token alterar exp reencodar e enganar o sistema Exemplo com HMAC (seguro) $payload = [ 'user' => 'joao' , 'exp' => time () + 300 ]; $secret = 'chave_super_secreta' ; $signature = hash_hmac ( 'sha256' , json_encode ( $payload [ 'user' ]) . '|' . $payload [ 'exp' ], $secret ); $payload [ 'sig' ] = $signature ; $token = base64_encode ( json_encode ( $payload )); Validação do lado do servidor $payload = json_decode ( base64_decode ( $_GET [ 'token' ]), true ); $check = hash_hmac ( 'sha256' , json_encode ( $payload [ 'user' ]) . '|' . $payload [ 'exp' ], $secret ); if ( ! hash_equals ( $check , $payload [ 'sig' ])) { die ( "Token inválido" ); }
AI 资讯
Composer Update Is Not Safe Anymore
Saturday morning. I opened Twitter and saw a tweet about the Laravel-Lang packages being compromised. My first reaction was simple: "I don't use that package." Then I opened composer.json on a project I work on and found this in require-dev : "laravel-lang/lang" : "^14.8" , "laravel-lang/publisher" : "^16.8" , That changed things. What Actually Happened The attack used laravel-lang packages as the distribution channel. And the sneaky part: the main repository branch looked completely clean. No suspicious commits, no new code. The malicious payload was pushed via git tags on forks . Most developers would not notice anything. Just a routine composer update , same as always. Once installed, the payload executed at autoload time . That means every php artisan command, queue worker, or web request running that codebase triggered the malware the moment PHP hit require_once __DIR__.'/../vendor/autoload.php' in public/index.php . Silently. No error, no red screen, nothing. The malware was a credential stealer. It searched the machine for: .env files from Laravel projects AWS access keys and session tokens SSH private keys GitHub CLI tokens NPM tokens Infrastructure secrets This is not a SQL injection that messes with your database rows. This is a key stealer that runs on your machine and takes everything it finds. Aikido Security caught it and reported it to Packagist. Packagist removed the affected versions. But if you ran composer update during that window, you were exposed. Why Supply Chain Attacks Are Different Classic Laravel security talks about SQL injection, XSS, CSRF. Those are attacks that come from outside users sending malicious input to your application. Supply chain attacks come from inside your own development process. The attacker does not need to find a vulnerability in your code. They need to compromise one developer account at one package maintainer. Every project depending on that package is now exposed. With AI tools, these attacks are getting more soph
AI 资讯
One Nullable Timestamp, Four Account States: Deriving User Status in Laravel
Most of today went into a user-management overhaul in kickoff — my Laravel starter kit. Flyout CRUD panels, bulk actions, permission assignment, and the piece I want to talk about: account status . Active, suspended, unverified, deleted. The interesting part isn't the feature. It's the modelling decision underneath it. Where do those four states actually live ? The trap: a status column The obvious move is a status enum column on users . Set it to suspended when you suspend someone, active when you reinstate, unverified until they verify their email, deleted when they're soft-deleted. It works. Until it doesn't. Now you've got a status column and an email_verified_at column and a deleted_at from soft deletes — and all three encode overlapping truths. Soft-delete a user and forget to flip status ? Now your database says the account is both active and trashed. Verify an email but the status update fails mid-request? Drift. Every place that mutates a user becomes a place that has to remember to keep status in sync. That's not a feature, that's a maintenance tax. The signals already exist. email_verified_at tells you verified-or-not. deleted_at (soft deletes) tells you removed-or-not. The only genuinely new state is suspended — an admin deliberately blocking sign-in. So that's the only thing worth storing. What we actually store: one nullable timestamp Schema :: table ( 'users' , function ( Blueprint $table ) { $table -> timestamp ( 'suspended_at' ) -> nullable () -> after ( 'email_verified_at' ); }); That's the whole migration. Not a boolean is_suspended — a nullable timestamp. Null means not suspended; a value means suspended and tells you when. A boolean throws that second fact away for free; the timestamp keeps it at no extra cost. Same instinct as email_verified_at and deleted_at — Laravel models "did this happen, and when" as a nullable timestamp everywhere, so we follow the grain of the framework. The behaviour on the model stays tiny: public function isSuspended
AI 资讯
Why an encrypted config backup breaks when you move servers — and how I fixed it in laravel-config-backup
Imagine you write a letter in a secret code that only your old house key can read. Then you move. You photocopy the coded letter, carry it to the new house… and realise the new key can't decode any of it. The letter is valid, just useless. That's effectively what happens when you back up encrypted values from a Laravel database and restore them onto a different server. I hit exactly this while working on laravel-config-backup today, so here's the problem and the fix. The real cause: Crypt is bound to APP_KEY When you store sensitive settings (think API tokens or OAuth secrets) in the database, you typically encrypt them with Crypt::encryptString() . Lovely — until you remember Crypt uses your app's APP_KEY as the key. A naive backup copies that ciphertext straight across: // Naive approach — move the ciphertext as-is $value = DB :: table ( 'settings' ) -> where ( 'key' , 'some.secret' ) -> value ( 'value' ); // this value is encrypted with the OLD server's APP_KEY The new server has a different APP_KEY . Try to decrypt → DecryptException: The payload is invalid . Your backup is technically complete but practically dead. The fix: decrypt on the way out, re-encrypt on the way in The decision is easy to state, hard to stay disciplined about: never carry ciphertext across a server boundary. Instead — On create : decrypt the values with the source server's APP_KEY , store plaintext inside the archive. Protect that archive with AES-256 and a password (a human-held secret, not the APP_KEY). On restore : re-encrypt the values with the destination server's APP_KEY before writing to the DB. Back to the analogy: you decode the letter, carry the plain letter in a locked briefcase (the password-protected archive), and re-encode it with the new house's lock on arrival. The briefcase handles security in transit — not the old code that's no longer relevant. I made that intent explicit right where the behaviour lives, in ConfigBackupService : /** * Config Backup & Restore. * * Bundl
AI 资讯
Shipping a Livewire 4 + Flux admin UI inside a package: four gotchas that 500'd on me
Bundling an admin UI inside a Laravel package is a different game from building one in an app. The app's conveniences — a compiled Vite manifest, a registered layout, your own Livewire components — aren't there. Today, getting the bundled admin UI in laravel-config-webhook to actually render meant walking through four separate 500s. Each one is a small, sharp lesson about the boundary between a package and its host app. 1. A Livewire 4 component name can't contain :: I registered the component with a namespaced-looking name and got a ComponentNotFoundException at runtime. The cause is subtle: under Livewire 4, a name containing :: triggers namespace resolution that ignores singly-registered components. So a "nice looking" name silently routes to a lookup that will never find it. The fix is to register a plain, dotted name: // ❌ looks tidy, but the "::" sends Livewire down a namespace path Livewire :: component ( 'config-webhook::webhooks' , Webhooks :: class ); // ✅ a flat dotted name resolves to the singly-registered component Livewire :: component ( 'config-webhook.webhooks' , Webhooks :: class ); Lesson: in a package, treat the component name as an identifier with framework-reserved characters — :: is not yours to use. 2. Flux ships Heroicons, not Pro/Lucide names The free tier of Flux ships Heroicons . Reach for a Pro-only or Lucide-style name and it throws at runtime. I'd used webhook , ellipsis , and list ; the free equivalents are bolt , ellipsis-horizontal , and queue-list . This is the same trap that bit my SSO package — which is exactly why I now guard it with a static test that reads the Blade and checks every icon against Flux's actual stub files. (Separate post on that.) If you ship a package UI with Flux, assume free-tier icons only unless you require Pro. 3. Don't @vite host assets that don't exist The bundled fallback layout @vite -d the host app's assets. In a fresh consumer (or the package's own workbench) there's no compiled manifest, so you get a
AI 资讯
A test that catches the bug your feature tests can't see
There's a class of bug that's maddening: it passes every test you have, then crashes in the user's face. I hit one in the admin UI of laravel-config-sso today, and the real fix wasn't changing an icon name — it was writing a test that could see the bug in the first place. The bug: wrong icon name, crashes only at runtime The admin UI uses Flux . Flux resolves icons through <flux:delegate-component> , and it throws for a name that doesn't exist: Flux component [icon.ellipsis] does not exist. It's an easy mistake. Flux ships Heroicons , not Lucide. So your Lucide reflexes lie to you: You type (Lucide) Flux wants (Heroicon) ellipsis ellipsis-horizontal trash-2 trash eye-off eye-slash Why feature tests don't catch it Here's the interesting part. I had a feature test that hits the admin route and asserts 200. Green. But the real UI crashes. How? Because in the headless test harness, Flux renders icons as no-ops. No real <flux:delegate-component> boots, so the icon name never gets resolved. The crash only surfaces under a full boot ( testbench serve ) — exactly where your automated tests don't go. Analogy: it's like a spell-checker that only runs when you print the document, not while you type. Your tests type away happily. The crash waits at the printer. The fix: a static test that reads the Blade and validates every icon Instead of relying on runtime, I wrote a Pest test that reads the Blade view, extracts every icon name (static and inside dynamic expressions), and asserts Flux actually ships a stub for each one: $fluxIconStubs = base_path ( 'vendor/livewire/flux/stubs/resources/views/flux/icon' ); it ( 'only references Flux icons that exist' , function () use ( $fluxIconStubs ) { expect ( is_dir ( $fluxIconStubs )) -> toBeTrue ( "Flux icon stubs not found" ); $view = file_get_contents ( __DIR__ . '/../../resources/views/livewire/sso-providers.blade.php' ); // Static `icon="name"` plus quoted tokens inside dynamic // `icon="{{ $cond ? 'eye-slash' : 'eye' }}"` expressio
AI 资讯
Making encrypted Laravel config backups portable across APP_KEYs
Here's a fun one. You build a package that backs up an app's config — the .env plus the settings stored encrypted in the database — into a single password-protected ZIP. The whole selling point is portability : take a backup on server A, restore it on server B, even when the two servers have different APP_KEY s. Then you write a test that actually changes the key during a restore, and it fails. The DB settings come back garbled. Turns out the bug wasn't in the encryption at all. It was in a cache I forgot was there. Today I shipped 1.1.0 of laravel-config-backup and this portability fix was the headline. Let me walk through it, because the lesson generalizes way beyond this package. Why APP_KEY portability is even a thing Laravel encrypts things with APP_KEY . Encrypted Eloquent casts, signed cookies, sessions — all of it keys off that value. So if you naively mysqldump a table with encrypted columns and load it onto another server, every encrypted column is now ciphertext that the new key can't decrypt. Dead data. The trick this package uses is to store the archive contents decrypted . When I export the database, rows go out through their casts , so an encrypted column becomes a plain value inside the ZIP (the ZIP itself is AES-256 password-encrypted, so it's not sitting around in plaintext). On import, each row is written back through the model , which means the cast re-encrypts it with whatever APP_KEY is active on the destination. Server A (key A) Archive (decrypted) Server B (key B) ──────────────── ─────────────────── ──────────────── settings.payload ──decrypt──▶ "Portable" ──import──▶ settings.payload (ciphertext A) (cast) (cast) (ciphertext B) Think of it like shipping furniture: you don't ship the assembled wardrobe through a doorway it doesn't fit, you flat-pack it and reassemble at the destination with the screws you have there. The restore sequence A restore that also brings a new .env has to be careful about ordering . Here's the real flow: public func
AI 资讯
Deploying Symfony 8 to cPanel Step by Step guide.
Table of Contents Introduction Double-check everything Configure your Environment Variables Install/Update your Vendors Clear your Symfony Cache Install symfony/apache-pack Update composer.json public directory Build the assets Update Kernel.php Upload the project to cPanel Final Thoughts Introduction I'm new to Symfony and recently, I deployed a Symfony app to a shared hosting environment running cPanel with no SSH access. I could not figure out the best way to do it, let alone find useful resources online as most of them are outdated and felt inefficient. I faced a lot of errors like: failing to load the app with a 500 Internal Server Error, some static assets not loading, etc. I figured it out in the end. This motivated me to write this post to reduce the headache for other Symfony newbies like me. Alright, let's get into it. Most deployment guides online assume you can run Composer, clear caches, execute migrations, and run Symfony commands directly on the server. In shared hosting environments, that is often not possible so, my examples will assume you don't have it installed on the server. 1. Double-check everything The first step to building for production is double-checking everything if it's in intact. Yes, this is very important. In my case, I was faced with some static image assets failing to load because of wrong reference which was ignored on dev mode. I had something like: asset('/images/<filename> ) which was working in dev mode but failed to load the image in prod. the paths had to be like: asset('images/'). This was after checking how I defined other assets. So avoid things like this before hand. 2. Configure your Environment Variables For this, we will use the dotenv:dump command which is not registered by default, so you must register first in your services: # config/services.yaml services : Symfony\Component\Dotenv\Command\DotenvDumpCommand : ~ Then, run the command below. After running this command, Symfony will create and load the .env.local.ph
AI 资讯
Building Video Heatmap Analytics with HyperLogLog in Postgres
The problem: counting unique viewers per second is a row explosion A viewer scrubs to 4:12 of a 9-minute trending clip, watches for 40 seconds, jumps back to the intro, then bounces. Multiply that by the few hundred thousand sessions a day that hit a mid-size aggregator and you get the question every product person eventually asks: which parts of this video do people actually watch, and how many distinct people watched each part? The naive answer is a watch_events table: one row per (user, video, second) . It works until it doesn't. A 9-minute video is 540 seconds. One viewer who watches the whole thing generates 540 rows. A million viewers across our catalog generate hundreds of millions of rows per day , and the only query anyone runs against them is COUNT(DISTINCT user_id) GROUP BY second . That COUNT(DISTINCT) is a sort-or-hash over the entire partition every single time someone opens the analytics tab. At TopVideoHub we aggregate trending video across Asia-Pacific, so a single popular clip can spike from zero to half a million sessions in an afternoon when it lands in the JP and KR feeds simultaneously. We did not want a fact table that grew by hundreds of millions of rows a day to answer a question whose answer is approximately fine. "Roughly 41,000 unique viewers saw the hook at 0:08" is just as actionable as "41,287". That tolerance for approximation is exactly what HyperLogLog is built for, and Postgres has a battle-tested extension for it. This post is the design we landed on: fixed-size HLL sketches, one per (video, time_bucket) , that you can merge, slice, and union across regions in milliseconds. The main app is PHP 8.4 on LiteSpeed behind Cloudflare, with our search layer on SQLite FTS5; the analytics store is a separate Postgres instance, and HLL is what made that store affordable. Why HyperLogLog instead of COUNT(DISTINCT) HyperLogLog estimates the cardinality of a set using a fixed amount of memory regardless of how many elements you throw at it. Th
AI 资讯
Build a versioned Laravel API with auto-generated OpenAPI docs in 10 minutes
TL;DR — We'll install dskripchenko/laravel-api , write one controller, and end up with a versioned API ( /api/v1/... ) and interactive OpenAPI 3.0 docs at /api/doc — generated from the docblock you'd write anyway. Then we'll ship a v2 without copy-pasting a single controller. The problem Two things rot in every growing Laravel API: Versioning. v1 ships, then v2 needs to change three endpoints but keep the other twenty. You either copy-paste a V2 folder (and now bugfixes live in two places) or bolt if ($version === 2) branches into your controllers. Docs. The OpenAPI spec drifts from the code the moment you merge. Annotation libraries ( #[OA\Get(...)] , giant YAML files) ask you to describe your API twice — once in code, once in attributes. This package's bet: your controller already describes itself . The method name, the request fields, the response shape — write them once, as a normal PHPDoc, and let the package derive routes and docs from it. Versioning becomes plain PHP inheritance. Let's build it. What we'll build A tiny tasks API: POST /api/v1/task/list — list tasks POST /api/v1/task/create — create one interactive docs at GET /api/doc (raw spec per version at /api/doc/{version} ) then a v2 that adds an endpoint without touching v1 Total: ~4 small files. Step 0 — Install composer require dskripchenko/laravel-api Publish the config (optional, but handy to see the knobs): php artisan vendor:publish --tag = laravel-api-config // config/laravel-api.php return [ 'prefix' => 'api' , // → /api/... 'uri_pattern' => '{version}/{controller}/{action}' , 'available_methods' => [ 'get' , 'post' , 'put' , 'patch' , 'delete' ], 'openapi_path' => 'public/openapi' , 'doc_middleware' => [], // lock down /api/doc here ]; Step 1 — Write a controller Nothing exotic — it extends the package's ApiController , which gives you response helpers ( success() , error() , validationError() , created() , noContent() , notFound() ). The docblock is the documentation : <?php namespace App\Api
AI 资讯
InfiniteWP's Strengths and Who It Fits — An Honest Review from a Competing Tool Builder
Among WordPress maintenance tools, InfiniteWP is one of the most established names. Released by Revmakx in 2011, the tool has been operated continuously for over a decade. It enjoys deep loyalty from agencies that have invested years building operational know-how around it . We at WP Maintenance Manager take a different approach, and our comparison pages outline where the two diverge. But before talking about differences, the strengths of InfiniteWP deserve to be stated honestly . Here are the five points where InfiniteWP fits an agency particularly well. 1. Over a decade of operational track record InfiniteWP's biggest structural advantage is trust built across more than a decade of continuous operation . Released in 2011 — one of the oldest tools in the space A large base of long-time English-speaking users with shared operational patterns Well-defined upgrade paths from older versions Backward compatibility with existing workflows and scripts has been maintained for years For agencies already invested in InfiniteWP, switching tools means more than "migration work" — it means rebuilding the operational know-how accumulated over years . Continuing to use a tool with proven track record is, in itself, a strength that long-running platforms have. The temporal depth that newer tools simply cannot replicate is a meaningful selection reason for conservative industries — those reluctant to substantially change established workflows. 2. Self-hosted — full control of the dashboard InfiniteWP is self-hosted by default , letting you place the dashboard on your own server (a cloud-hosted version is available separately). Host on infrastructure you own Complete data ownership No dependency on external SaaS Arbitrary customization possible When the constraint is "client data must not sit in a third-party SaaS" or "our security policy doesn't permit SaaS," InfiniteWP's self-hosted architecture is a direct answer. If your team has experience operating PHP / WordPress infrastructu
AI 资讯
Why I Stopped Using reset() and end() in PHP (And What I Use Now)
If you have been writing PHP for a year or two, you have almost certainly written something like this: $items = getFilteredOrders (); $first = reset ( $items ); $last = end ( $items ); It works. It runs. It looks fine in code review. And it contains a subtle bug waiting to happen. The problem with reset() and end() Both functions move PHP's internal array pointer as a side effect. PHP arrays have a hidden cursor that tracks "the current position" in the array. Functions like current() , next() , prev() , and each() depend on where that cursor sits. reset() moves it to the first element. end() moves it to the last. This is harmless in an isolated script. But in a real application, the same array often passes through multiple functions — and any function that relies on the cursor position after your call will get unexpected results. Here is a concrete example: function getFirstActiveOrder ( array $orders ): ?array { // Moves the pointer to the first element $first = reset ( $orders ); foreach ( $orders as $order ) { if ( $order [ 'status' ] === 'active' ) { return $order ; } } return null ; } At first glance this looks fine. But foreach in PHP actually resets the pointer to the beginning before iterating — so in this simple case you get lucky. The bug shows up in less obvious situations: when you call reset() inside a function that the caller is already iterating with current() / next() , or when you use end() to peek at the last item while a foreach is in progress on the same array reference. The deeper issue: reset() and end() return false on an empty array. But false might also be a legitimate value stored in your array: $flags = [ true , false , true ]; $last = end ( $flags ); // returns false — but is this "empty array" or "the value false"? You have to write: if ( $flags === [] || end ( $flags ) === false ) { ... } Which is already awkward. And it still mutates the pointer. The modern solution: array_key_first() and array_key_last() PHP 7.3 introduced two functi