AI 资讯
Three PHP-FPM failure modes and how to actually diagnose them
Tuning guides talk about throughput. Nobody pages you about throughput. They page you about symptoms, and the useful skill is mapping a symptom back to a cause before you spend money on hardware. Three failure modes account for most of what I find on inherited servers. Each has a distinct signature. The 502 nobody can reproduce Server has 8GB. PHP-FPM is set to 100 workers. Each worker uses 60MB under load. That's 6GB of PHP, plus MariaDB, plus Nginx, plus the OS. Under normal traffic you never approach 100 workers, so it looks fine for months. Then a marketing email goes out, concurrency spikes, and the kernel runs out of memory. The OOM killer picks a process and terminates it, usually the biggest one, which is a PHP-FPM worker holding an in-flight request. User gets a 502. The application log has nothing, because the process died before it could write anything. Nginx logs recv() failed (104: Connection reset by peer) . Ten minutes later everything looks normal. sudo dmesg -T | grep -i "killed process" sudo journalctl -k | grep -i oom Hits there mean you don't have a mystery. You have a pm.max_children value nobody checked against real memory. The site that degrades all day and resets overnight TTFB is 180ms at 8am. By 4pm it's 900ms. Nobody deployed. Overnight it's fast again because something restarted PHP-FPM. That's OPcache running out of room. When the cache fills, it stops caching new scripts or wipes and rebuilds, and every miss pays full parse-and-compile again. It degrades gradually, which is why it goes unnoticed for months. The counters are oom_restarts and hash_restarts from opcache_get_status() . Here's the part that trips people up. OPcache state is per SAPI. Run that function from the CLI and you're reading the CLI cache, which is empty, separate, and tells you nothing about your site. You have to ask through PHP-FPM. <?php // drop in webroot, lock to your IP, delete when done $allowed = [ '203.0.113.42' ]; if ( ! in_array ( $_SERVER [ 'REMOTE_ADDR'
AI 资讯
WebForms.php 2.1 Released - DeepSeek Converted and Qwen Evaluated
WebForms.php 2.1 has been released as the PHP back-end implementation of WebForms Core 2.1. This release is different from a typical porting story. The PHP implementation was converted from the C# implementation of WebForms Core using DeepSeek, and then independently evaluated with Qwen. The process was not simply: C# → PHP It was: C# → DeepSeek conversion → manual review → Qwen evaluation → corrections → testing → release This article explains that process and some of the interesting problems that appeared during the conversion. What is WebForms.php? WebForms.php is the PHP back-end part of WebForms Core. WebForms Core is a server-driven web technology based on the Commander–Executor concept. The server generates commands that describe UI operations and execution flow. WebFormsJS , running in the browser, interprets and executes those commands. The WebForms class itself does not manipulate the browser DOM directly. It generates the WebForms Core command structure. This makes the WebForms class particularly suitable for implementation in multiple programming languages. The PHP implementation provides the same WebForms Core programming model for PHP applications. Why Convert the C# Implementation? WebForms Core already has implementations for multiple programming languages. The C# implementation is the primary reference implementation and contains a large number of methods for: DOM manipulation event management Fetch operations conditions loops state management storage browser history WebSockets SSE templates selectors Action Controls and other WebForms Core operations The WebForms class mainly generates command strings. Because of this architecture, the fundamental logic does not need to be redesigned for every language. The objective of the PHP implementation was therefore to preserve the behavior and output of the C# implementation while adapting the code to PHP conventions and language capabilities. DeepSeek Conversion I provided the C# implementation and related
开源项目
Akeneo PIM v7 Reaches End of Support on 30 September 2026. Here Are the Options
The open-source PIM landscape changed twice in eighteen months. Most comparison articles still ranking for it haven't caught up. Current state, September 2026. The date Akeneo has published 30 September 2026 as the end of support for PIM v7. That is twenty-seven days from the date of writing. It is worth stating precisely what that does and does not mean, because both halves are currently circulating in isolation. It does mean a specific version reaches the end of its supported life on a specific date. Teams running v7 have an upgrade decision with a deadline attached. It does not mean Akeneo is discontinued or unsupported. Akeneo's own help centre states that the Community Edition continues to be supported. The 30 September date attaches to v7 across editions, not to the Community Edition as a product. Both are true simultaneously. Plan around the first. Ignore anyone selling urgency based on the second. The change most articles missed While attention was on Akeneo, the larger licensing shift happened elsewhere. Pimcore's Community Edition is no longer GPLv3. With Platform version 2025.1, Pimcore moved the Community Edition to the Pimcore Open Core License (POCL). Version 2024.4 was the last GPLv3 release. Under POCL, the Community Edition is free for non-production use, for non-profits, and for companies below EUR 5 million in annual revenue . Above that threshold, production use requires a commercial licence. This is the change that catches teams out. An evaluation done in 2023 recorded Pimcore CE as free and GPLv3. A company that has since grown past EUR 5M has a different licensing position than the one in its comparison sheet. Source: pimcore.com/en/products/edition/community Most ranking "open source PIM compared" articles still describe Pimcore CE as GPLv3. Publication dates are worth checking on anything in this space, including this article. The systems as they stand Akeneo Community Edition Licensed under OSL 3.0. Mature, widely deployed, and backed by th
AI 资讯
How the WordPress transient API works, and when `wp transient delete` actually helps
WordPress ships with a built-in way to store data temporarily — save something for a fixed window of time, and it stops being valid once that window closes. This is the transient API, and both WordPress core and countless plugins lean on it to cache things like external API responses or the results of expensive calculations. It's a genuinely useful mechanism, but used without understanding how it actually behaves, expired entries can pile up and quietly bloat the database. Note: the transient API is WordPress core's name for a small set of PHP functions — set_transient() , get_transient() , delete_transient() — built around the idea of a cache entry with an expiration. How a transient actually works Saving a transient means specifying three things: a value, a key, and an expiration in seconds. set_transient ( 'weather_data' , $api_response , 3600 ); // cache for one hour Where that value actually gets stored depends on the site's setup: Default setup (most shared hosting environments): it lands in the wp_options table as a row named _transient_<key> , with a matching _transient_timeout_<key> row holding the expiration With a persistent object cache (a plugin backed by Redis or Memcached): the value goes to that cache layer instead of wp_options When get_transient() is called, WordPress compares the timeout value against the current time and returns false if the entry has expired. At that point, the design intends for the stale row to be cleaned up automatically — but that cleanup isn't as reliable as it sounds. Why expired entries stick around In theory, an expired transient should disappear. In practice, wp_options can accumulate a large number of long-expired rows. Two things typically cause this: get_transient() is never called again for that key. The automatic cleanup described above is passive — it only fires when something actually tries to read the value and finds it expired. It isn't an active sweep. If a plugin sets a value once and never checks it again, t
AI 资讯
`wp db check` / `wp db optimize` — the database health commands that get overlooked
A WordPress database doesn't tidy itself up over time. Spam comments pile up, expired transients linger, post revisions accumulate, and tables left behind by uninstalled plugins never quite go away. All of that adds up to bloated tables, and occasionally to actual table corruption. This is territory the admin dashboard barely shows you — but WP-CLI reaches it directly with two short commands: wp db check and wp db optimize . Note: WP-CLI's wp db subcommands operate directly on the MySQL (or MariaDB) database WordPress uses, without going through the admin dashboard. Connection details are read automatically from wp-config.php . wp db check — verifying table health wp db check Under the hood, this runs the equivalent of mysqlcheck --check against every table and reports each one's status: wp_posts OK wp_options OK wp_postmeta OK If a table comes back corrupt , SELECT and INSERT queries against it start failing. That can surface as something oddly specific — a single page going blank, one particular post refusing to save — with no obvious connection to a database problem. Running wp db check on a regular schedule catches that kind of issue before it turns into a visible symptom. wp db optimize — defragmenting tables wp db optimize This one runs the equivalent of mysqlcheck --optimize , applying OPTIMIZE TABLE to each table. Tables that see a lot of row deletions and updates tend to become fragmented on disk over time. OPTIMIZE TABLE rebuilds the table and reclaims the space that deleted rows used to occupy. Note: behavior differs by storage engine. WordPress's default engine, InnoDB , handles OPTIMIZE TABLE internally as a table rebuild (roughly equivalent to ALTER TABLE ... FORCE ), which both defragments the table and refreshes its statistics. The older MyISAM engine doesn't reclaim space from deleted rows automatically at all — that disk space only gets released once OPTIMIZE TABLE runs. Some installs set up through a hosting provider's one-click installer still ca
AI 资讯
Using WP-CLI aliases to switch between multiple WordPress environments safely
Anyone managing several WordPress environments — production, staging, or separate installs for different languages — ends up re-typing SSH connection details and install paths every time they run a command. Building that connection string by hand each time invites mistakes: a copy-paste error, or reusing a stale path, can send a command to the wrong environment entirely. That risk matters most for write commands — bulk plugin updates or database operations — where hitting the wrong target has real consequences. WP-CLI has a built-in feature for exactly this problem: aliases. Note: A WP-CLI "alias" assigns a short name (like @production ) to a set of connection details — an SSH target and a WordPress install path. Once registered, that short name replaces the full connection string on every subsequent command. Where aliases live Aliases are registered in one of two config files: Project-level : wp-cli.yml in the working directory Global : ~/.wp-cli/config.yml in the home directory If the same alias name exists in both, the project-level file takes precedence. If the same environments get used across multiple projects, consolidating aliases in ~/.wp-cli/config.yml keeps things easier to manage. Example registration ( config.yml ): @production : ssh : user@production.example.com:22 path : /var/www/production/wordpress @staging : ssh : user@staging.example.com:22 path : /var/www/staging/wordpress ssh specifies the username, host, and port; path points to the WordPress install directory. This assumes key-based SSH authentication — passwords should never be written into config.yml . If this file is tracked in a repository, an accidental commit turns it into a leak vector for connection details, so keep it in .gitignore , or store it outside the repository in the home directory instead. Calling a single alias Once registered, commands that previously required an ssh login first can run in a single line from your local machine: wp @production plugin list wp @staging plugin
AI 资讯
When HTTP Retries Become Dangerous: Idempotency in Symfony Without the Fairy Tales
Retries are one of those things that look harmless until the first time they duplicate a real business operation. A request times out, so the client retries it. Reasonable. But what if the first request actually reached the server? What if the application already created the order, reserved the stock, sent the message, or called a payment provider — and only the response was lost? From the client's point of view, the request failed. From the application's point of view, it may already be finished. Send the same request again and you can get the worst kind of bug: one that is technically understandable, difficult to reproduce, and very expensive in production. This is the problem that pushed me to build HttpIdempotencyBundle , a small Symfony bundle for explicit HTTP request idempotency. But the interesting part is not the bundle itself. The interesting part is everything that has to be true before we can safely say: "This request is a retry of the same operation, so we should not execute it again." And just as importantly, what we cannot guarantee. A timeout does not mean the operation failed Consider a simple endpoint: #[Route('/orders', methods: ['POST'])] public function createOrder (): JsonResponse { $order = $this -> orderService -> create (); return new JsonResponse ([ 'id' => $order -> getId (), ], 201 ); } Now imagine this sequence: Client -> POST /orders Server -> creates order #742 Server -> sends 201 response Network -> connection dies Client -> sees timeout Client -> retries POST /orders Nothing unusual happened. The client did exactly what clients often do after a timeout. The server did exactly what it was asked to do. And yet, unless we have another mechanism in place, we may now create order #743 as well. The key idea is simple: transport failure and business-operation failure are not the same thing. HTTP cannot always tell the client whether the operation happened. Give the operation an identity A common solution is an Idempotency-Key . The client g
AI 资讯
We put an MCP endpoint in 49 business apps. Here is what a read-only key can and cannot do to an invoice register.
We build small self-hosted business tools, and since our 3.0 release every one of them except our AI client answers the Model Context Protocol at POST /mcp . Forty-nine of them. That was a large enough change, applied uniformly enough, that the interesting engineering question stopped being "how do we add MCP" and became "what should a language model be allowed to do to a live invoice register." This post is about the second question, because it is the one that actually matters and the one most MCP integrations answer by accident. The boring part first: the handshake There is nothing vendor-specific in it. Three facts: The address. https://your-install/mcp - your server, your domain. The key. An Authorization: Bearer apk_... header. The transport. MCP over streamable HTTP, stateless. One request in, one response out. That is the whole contract. In Claude it is one CLI line: claude mcp add --transport http invora https://your-install/mcp \ --header "Authorization: Bearer apk_xxxx" In the OpenAI Responses API it is one entry in the tools array: { "type" : "mcp" , "server_label" : "invora" , "server_url" : "https://your-install/mcp" , "authorization" : "apk_xxxx" , "require_approval" : "never" } Clients that keep servers in a config file take the same three fields under a different set of key names. n8n's MCP Client node takes the URL and the same Authorization header. And if you would rather not use a client at all, it is plain JSON-RPC 2.0 over one POST: curl -X POST https://your-install/mcp \ -H "Authorization: Bearer apk_xxxx" -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' We implemented the protocol rather than an integration with a particular vendor, which means clients that do not exist yet will work too. That is the main argument for MCP over building N bespoke connectors, and it is a good one, but it is not what this post is about. The part that took the actual thinking Once your invoice register speaks a protocol tha
AI 资讯
Distributed Background Processing: Scaling Temporal Workflows with Laravel
Laravel's queue system is excellent. Redis-backed queues and supervisors can handle millions of standard jobs efficiently. However, when background processing evolves into complex, multi-day, retry-sensitive state machines, standard queues begin to show limits. Consider a multi-step user onboarding flow: Send a welcome email. Wait 3 days. Check if the user uploaded a profile picture. If not, send a reminder. Wait another 4 days. If still incomplete, flag the account for manual sales outreach. Implementing this with standard Laravel jobs requires writing complex database state tracking, configuring multiple delayed dispatch loops, and managing manual retry intervals. If a server reboots mid-process, tracking which step a user was on becomes an operational nightmare. Temporal solves this. It is a workflow orchestration engine that guarantees state progression. It allows you to write standard PHP code while Temporal handles state persistence, timeouts, queryable statuses, and complex retries. Here is how to integrate Temporal into your Laravel application. Core Architecture: Workflows vs. Activities Temporal separates execution logic into two distinct concepts to ensure reliability and fault tolerance: Workflows : The orchestrator. Workflows must be deterministic . They dictate the flow of execution, handle sleep intervals, and coordinate steps. Because they are deterministic, they must not interact directly with external systems, databases, or random functions. Activities : The execution layer. Activities can be non-deterministic. They perform the actual work: making database queries, querying third-party APIs, sending emails, or writing files. Setting Up Temporal in Laravel To communicate with a Temporal cluster, install the official Temporal PHP SDK via Composer: composer require temporal/sdk Next, configure your Temporal environment. In your .env , define the location of your Temporal address (by default, a local installation runs on port 7233 ): TEMPORAL_ADDRESS=1
AI 资讯
The Whale Metaphor: How OOP's Four Pillars Actually Work in WordPress
In the age of AI engineering and vibe coding, almost nobody mentions OOP anymore. But what if children were never taught prefixes, roots, and suffixes — the architecture of words — or how a sentence is properly built? Will AI agents really be enough for the specialists of tomorrow, if those specialists never learned the grammar underneath? Dive into OOP in WordPress development practice → (original source, featuring the four whales example) Most WordPress developers learn Object-Oriented Programming the hard way: by staring at WP_Widget, WP_Query, or WP_Post and reverse-engineering why core is built the way it is. Textbooks explain encapsulation, abstraction, inheritance, and polymorphism with abstract diagrams that rarely survive contact with real code. Here's a different way to think about it — using a whale. A whale keeps its vital organs protected inside its body, dives into depths where the mechanics of survival are invisible from the surface, passes traits down to its calf, and adapts its behavior differently depending on the environment it's in. Swap "whale" for "class," and you've basically described the four pillars of OOP. Let's walk through each one with WordPress-specific code, then look at how the same principles scale from a five-page brochure site to an enterprise platform. Why OOP Matters in WordPress at All WordPress was procedural for most of its early life, and plenty of plugins still are. But once your project outgrows a handful of files, procedural code starts fighting you: global state leaks everywhere, the same logic gets copy-pasted into three different hooks, and a single typo in a variable name three files away breaks something unrelated. OOP fixes this by grouping data and behavior together into objects instead of scattering functions and passing arrays between them. WordPress core made this bet a long time ago — WP_Widget, WP_Query, and WP_Post are all classes — and the four principles below are the foundation that makes classes trustwort
AI 资讯
How to generate WCAG-compliant ALT text for WordPress images without sending them to a vendor's black-box API
If you've ever tried to fix accessibility on an old WordPress site, you know the drill: hundreds of images in the Media Library, most with empty alt attributes, and a WCAG 2.1 audit (or a client demanding one) breathing down your neck. Writing alt text by hand for 400 images is not a fun Tuesday. Every "AI alt text" SaaS I looked at wanted a monthly subscription, routed my images through their own servers, and gave me zero control over which model actually looked at the picture. This post is about the plugin I built to fix that for my own sites, and the handful of implementation details that turned out to matter more than expected. The actual problem WCAG 2.1 Success Criterion 1.1.1 requires non-text content to have a text alternative. In WordPress terms: every attachment post of MIME type image should have _wp_attachment_image_alt set to something meaningful, not "IMG_4821.jpg" and not empty. Doing this with a vision-capable LLM is trivial in principle — send the image, ask for a short description, save it as the alt attribute. The part that's not trivial, if you don't want another recurring SaaS bill and don't want to hand a third party your whole media library, is: whose API key, which model, and where does the image actually go. Design decision: BYOK, not a hosted service The plugin ( Alt Text BYOK ) doesn't call any server of mine. It calls whatever OpenAI-compatible chat/completions endpoint you configure, with your own API key. That's the entire trust model: your images go from your WordPress install directly to the provider you already chose (OpenAI, or any of the growing list of OpenAI-compatible vision endpoints), and nowhere else. The settings are deliberately just four fields: function atbyok_default_settings () { return array ( 'api_base' => 'https://api.openai.com/v1' , 'api_key' => '' , 'model' => 'gpt-4o-mini' , 'language' => 'English' , 'overwrite_existing' => '0' , 'license_key' => '' , ); } api_base is the detail that matters most for portability:
AI 资讯
Stop rewriting your API responses in Laravel (Use this Trait instead)
If you are building API-driven applications, nothing clutters up your controllers faster than manually typing out response()->json(...) arrays every single time you need to return data or throw an error. When you have inconsistent response structures, your frontend (and the developers consuming your API) will constantly have to guess whether the data is nested under ['data'] , ['payload'] , or just at the root of the object. The cleanest way I've found to standardize this across an entire application is by creating a dedicated ApiResponse trait. Instead of rewriting your JSON structure in every controller method, create this trait in your app/Traits directory: namespace App\Traits ; use Illuminate\Http\JsonResponse ; trait ApiResponse { protected function success ( mixed $data , ?string $message = null , int $code = 200 ): JsonResponse { return response () -> json ([ 'status' => 'success' , 'message' => $message , 'data' => $data ], $code ); } protected function error ( string $message , int $code = 400 , array | string $errors = []): JsonResponse { // Force errors into an array format for consistent frontend parsing $formattedErrors = is_string ( $errors ) ? [ $errors ] : $errors ; return response () -> json ([ 'status' => 'error' , 'message' => $message , 'errors' => $formattedErrors ], $code ); } } Next, simply use this trait inside your base Controller.php . Now, your actual endpoints become incredibly readable and strictly standardized: namespace App\Http\Controllers ; use App\Models\Task ; use Illuminate\Http\Request ; use Illuminate\Http\JsonResponse ; use Throwable ; class TaskController extends Controller { public function store ( Request $request ): JsonResponse { $validated = $request -> validate ([ 'title' => 'required|string|max:255' , 'description' => 'nullable|string' ]); try { $task = Task :: create ( $validated ); return $this -> success ( $task , 'Task successfully generated' , 201 ); } catch ( Throwable $e ) { // Note: Exposing raw exception messa
开发者
I Built a Discord Server Discovery Platform
I Started Building a Discord Server Directory I’ve spent a lot of time around Discord communities, and one thing has always bothered me. Finding a good Discord server is harder than it should be. There are thousands of communities for gaming, anime, roleplay, technology, social groups and pretty much every niche you can think of. But finding the right one usually means jumping between invite links, old posts, server lists and search results. At some point I thought, why not build a better way to discover them? That’s how I started working on Dizord. The first version was pretty simple. I wanted a place where a server could be listed, people could discover it, and everything could be organized around interests instead of just one giant list of servers. Then the project started getting bigger. More servers meant more categories and tags. More tags meant better search and filtering. Server information changes constantly, so keeping listings updated became another problem to solve. I’m building the backend with Laravel and working with the Discord API to handle server information and synchronization. There are also a lot of small things behind the scenes that aren't obvious when you simply open a server listing page. One of the things I'm currently working on is making discovery better for smaller communities. A server shouldn't need tens of thousands of members just to be discoverable. The goal is pretty simple: Make it easier to find a Discord community you'll actually want to stay in. The project is still evolving, but the current version is live: https://dizord.com I'm still experimenting with search, categorization, server activity and ways to make a large directory useful instead of overwhelming. If you're building a directory, marketplace, or any project with thousands of constantly changing pages, I'd also be interested in hearing how you handle discovery and indexing at scale.
AI 资讯
How I Debugged a phpMyAdmin 500 Error While Importing a Large SQL File on Laragon
I recently ran into a weird issue while working on a Laravel project on Windows using Laragon . Everything was working fine until I tried to import a database through phpMyAdmin. Instead of an SQL error, phpMyAdmin simply returned: Internal Server Error The server encountered an internal error or misconfiguration... No useful message. Just HTTP 500. My SQL file was around 97 MB , so at first I thought it was probably a PHP upload limit issue. It wasn't that simple. Here is how I debugged it. 1. Check which PHP configuration is actually running From Laragon Terminal: php --ini Then I checked the important error settings: php.exe -r "echo 'error_log=' . ini_get('error_log') . PHP_EOL;" php.exe -r "echo 'log_errors=' . ini_get('log_errors') . PHP_EOL;" php.exe -r "echo 'display_errors=' . ini_get('display_errors') . PHP_EOL;" My output was: error_log=D:/C-data/laragon/tmp/php_errors.log log_errors=1 display_errors=1 One small Laragon/Git Bash issue I also found was: type php returned: php is aliased to `winpty php.exe' Because of that, commands like: php -i | grep ... sometimes returned: stdout is not a tty Using php.exe directly avoids that problem. 2. Check the PHP error log My PHP error log was: D:/C-data/laragon/tmp/php_errors.log I reproduced the import error and checked it: tail -n 50 /d/C-data/laragon/tmp/php_errors.log Nothing useful appeared. That was an important clue. 3. Make sure browser PHP and CLI PHP use the same php.ini I created a temporary file: <?php phpinfo (); Then opened it through the browser. Important values were: Server API: CGI/FastCGI PHP Version: 8.4.4 Loaded Configuration File: D:\C-data\laragon\bin\php\php-8.4.4-nts-Win32-vs17-x64\php.ini My PHP limits were already high enough: upload_max_filesize = 512M post_max_size = 512M memory_limit = 512M max_execution_time = 36000 So the 97 MB SQL file should have been allowed by PHP. 4. Check Apache logs I located the Apache error log with: grep -Ri "ErrorLog" /d/C-data/laragon/etc/apache2 /d/C-da
AI 资讯
When `@deprecated` cries wolf: Making Shopware’s next major upgrades easier
When PHPStan reports that your extension calls a deprecated method, the expected next step is quite clear: find the replacement and migrate your code. But what if there is no replacement? Consider Context::scope() . Previously, its planned change for Shopware 6.8 was announced like this: /** * @deprecated tag:v6.8.0 - reason:new-optional-parameter - parameter $states will be added */ public function scope ( string $scope , \Closure $callback ) : mixed Static analysis sees @deprecated and reports every call to the method. However, the method is not going away. A new optional parameter will be added, so existing calls will continue to work without any changes. There is no alternative API to migrate to and no warning to resolve. In this situation, @deprecated is effectively crying wolf. With Shopware 6.7.14.0, we are changing how these planned API changes are communicated. Real deprecations remain deprecations. Other backward-compatibility changes are now described with dedicated, structured PHP attributes. The immediate result is less noise for extension developers. Additionally, the new attributes give us a foundation for preparing extensions for Shopware 6.8 - and future major releases - before those releases arrive. TL;DR Shopware now uses two different signals for two different purposes: @deprecated means that an API is obsolete and will be removed or replaced. Extension developers need to migrate away from it. BC-change attributes describe a future change to an API that remains available, such as a new parameter, a narrower return type, or a class becoming final. The attributes also distinguish between changes that affect code calling an API and changes that affect classes extending it. This means deprecation warnings become trustworthy and actionable again, while planned contract changes carry enough structured information for PHPStan, Rector, IDEs, and other tools to reason about them. We were asking @deprecated to do two different jobs The commonly understood
AI 资讯
Per-user two-factor auth in CakePHP with CakeDC/Users (opt-in, one method)
CakeDC/Users gives you TOTP two-factor authentication almost for free: flip one config key and every login grows a "enter your 6-digit code" step. The catch is that word every . The built-in flow is all-or-nothing — turn it on and all your users are forced through the OTP challenge on their next login, whether they ever set up an authenticator app or not. Lock yourself out on a fresh install and you'll find out fast. What most apps actually want is the model you see everywhere else: 2FA is off by default , and each user opts in from their own account settings. This post shows how to get there with a surprisingly small change — one overridden method — plus a self-service enrolment screen and one QR-code gotcha that will bite you on modern dependencies. The one insight: isRequired() CakeDC/Users decides whether to demand the OTP step through an OneTimePasswordAuthenticationCheckerInterface . The default implementation, DefaultOneTimePasswordAuthenticationChecker , answers "is 2FA required for this request?" — and once the authenticator is enabled in the login flow, it answers yes for everybody . That checker is a swappable dependency. So "per-user 2FA" reduces to: keep the default behaviour, but also require that this specific user has opted in. One method: <?php declare ( strict_types = 1 ); namespace App\Authentication ; use CakeDC\Auth\Authentication\DefaultOneTimePasswordAuthenticationChecker ; class PerUserOneTimePasswordAuthenticationChecker extends DefaultOneTimePasswordAuthenticationChecker { /** * @param array<mixed>|null $user User data. */ public function isRequired ( ?array $user = null ): bool { // Default rules AND the user enrolled. return parent :: isRequired ( $user ) && ! empty ( $user [ 'two_steps' ]); } } parent::isRequired() keeps every rule CakeDC already applies (the authenticator is on, the user has a verified secret, remember-me isn't skipping it, …). We just && a per-user flag on top. Users who never enrolled fail the two_steps check and log
AI 资讯
Your PrestaShop hook renders nothing, and nothing is logged
A module hook that returns an empty string looks exactly like a module hook that was never called. PrestaShop gives you nothing to tell them apart: no error, no log entry, no stack trace, no fallback text. The page renders fine. Your block is just absent. We spent three releases of one module chasing this, and the cause turned out to be three different mechanisms stacked on top of each other. Each one alone is enough to make output vanish silently. This is what they are, in the order we peeled them off. The setup The module registers displayHeader and renders a small template: a <script> block that carries a public site key into the page, and a <style> block that hides a third-party badge. Roughly: public function hookDisplayHeader ( $params ) { $this -> context -> smarty -> assign ([ 'recaptcha_pubkey' => $this -> getActivePublicKey (), 'recaptcha_hide_badge' => $hideBadge , ]); return $this -> display ( __FILE__ , 'views/templates/front/header_script.tpl' ); } Deployed, cache cleared, hook registered, Design > Positions shows the module attached. Page source: nothing. Not the script, not the style, not even a stray whitespace. Mechanism 1: core swallows the exception Hook::callHookOn() wraps every module hook call in a try/catch. When debug mode is off, it catches whatever the hook throws and returns an empty string. No error, no log, no trace. That is a defensible design decision — one broken module should not take down a storefront — but as a debugging experience it is brutal. Every possible failure inside your hook, from a typo to a missing file to a template that will not compile, arrives at your screen as the exact same symptom: nothing. The first thing to do, before theorising about causes, is to stop letting core swallow it: try { return $this -> display ( __FILE__ , 'views/templates/front/header_script.tpl' ); } catch ( Throwable $e ) { $message = 'mymodule header_script.tpl render failed: ' . $e -> getMessage () . ' in ' . $e -> getFile () . ':' . $e -> g
AI 资讯
Credits, plans and quotas in Laravel with Larameter
If your app sells an allowance, a number of credits a month, or a number of documents, or a number of anything. Whatever it is, you end up writing a balance somewhere, a reset when the period rolls over, a check before the expensive call, and a usage screen that has to agree with all of it. None of that is hard on its own. What gets you is that the pieces drift. The plan says a thousand a month, the reset runs on the first of the month, the subscription renews on the 18th, and the screen sums a table that the charging code stopped writing to two features ago. And then somebody adds a weekly cap and now there are two numbers per plan to keep consistent, times seven plans. So after repeating the same on many apps, just created Larameter. It's basically what you see in Claude or OpenAI subscription plans. It meters credits against a plan, enforces ceilings on things that exist rather than things that are spent, and works out which plan an account is on instead of storing it. How to install Just install the package via composer as usually: composer require edulazaro/larameter php artisan vendor:publish --tag = larameter-config php artisan vendor:publish --tag = larameter-migrations php artisan migrate Then add the trait to whatever you bill. An organisation, a user, a workspace: the package does not care, and it does not need a column on your table. use EduLazaro\Larameter\Concerns\HasCredits ; class Organization extends Model { use HasCredits ; } The account row appears the first time you touch it. What are allowances One period is rarely enough. A monthly figure alone lets a bad afternoon eat the month, so you want a weekly cap on top, and maybe a per-session one. Declare those windows once: 'windows' => [ 'session' => [ 'minutes' => 300 , 'anchor' => 'rolling' , 'share' => 0.04 ], 'weekly' => [ 'days' => 7 , 'anchor' => 'fixed' , 'share' => 0.25 ], 'monthly' => [ 'months' => 1 , 'anchor' => 'fixed' , 'share' => 1 ], ], And then a plan grants 1 figure , which every wi
AI 资讯
Building a Personal Blog with Laravel: A Real World Project
A personal blog sounds like a simple Laravel project. Create posts, show them on the homepage, and you are done. But once you start adding search, categories, tags, comments, SEO, authentication, analytics, and an admin panel, things become much more interesting. I built this Laravel Personal Blog as a real world project to explore those problems instead of building another basic CRUD application. The complete source code is available on GitHub: https://github.com/arafat-web/laravel-personal-blog Table of Contents What Is This Project? Technology Stack Main Features Project Structure How Visitor Analytics Works SEO and Content Management How to Run the Project What I Learned Final Thoughts What Is This Project? This is a complete single-author blogging platform built with Laravel. It includes both a public blog and a custom admin panel. The project was built without additional application packages, so most of the important functionality is visible in the codebase itself. The public side contains: Homepage Blog posts Categories Tags Search Comments RSS feed Sitemap SEO metadata Post view tracking The admin panel contains: Dashboard Post management Category and tag management Comment moderation User management General settings SEO settings Visitor analytics Technology Stack The project uses: PHP 8.3+ Laravel 13.17 MySQL or SQLite Blade Eloquent ORM JavaScript CSS PHPUnit The current project configuration requires PHP 8.3 and Laravel 13.17. Main Features The project goes beyond basic CRUD. For example, posts can have categories, tags, comments, authors, featured images, publishing status, and view counts. The Post model defines these relationships using Eloquent: public function user (): BelongsTo { return $this -> belongsTo ( User :: class ); } public function categories (): BelongsToMany { return $this -> belongsToMany ( Category :: class ); } public function tags (): BelongsToMany { return $this -> belongsToMany ( Tag :: class ); } public function comments (): HasMa
AI 资讯
Building a Custom REST API in WordPress the Right Way
WordPress is often treated as a traditional CMS, but its REST API makes it possible to use WordPress as the backend for applications, dashboards, mobile clients, automation systems, and external services. The difficult part isn't registering an endpoint. The difficult part is designing the endpoint so that authentication, authorization, validation, error handling, and data access are all handled correctly. A production API needs a contract. It needs to know: Who can access it What data they can access What input is accepted What output is returned What happens when something fails Here's a practical approach. Register a Custom Route A basic WordPress REST API route can be registered with register_rest_route() . add_action ( 'rest_api_init' , function () { register_rest_route ( 'myplugin/v1' , '/posts' , [ 'methods' => WP_REST_Server :: READABLE , 'callback' => 'myplugin_get_posts' , ]); }); This creates an endpoint similar to: /wp-json/myplugin/v1/posts The namespace matters. Using: myplugin/v1 gives the API a version boundary. If the response structure changes later, a new version can be introduced without immediately breaking existing clients. Don't Put Authorization Inside the Callback A common beginner implementation does everything inside the callback: function myplugin_get_posts () { if ( ! current_user_can ( 'manage_options' )) { return new WP_Error ( 'forbidden' , 'Access denied' , [ 'status' => 403 ] ); } // Query data... } This works, but WordPress provides a cleaner place for the permission decision. Use permission_callback . register_rest_route ( 'myplugin/v1' , '/posts' , [ 'methods' => WP_REST_Server :: READABLE , 'callback' => 'myplugin_get_posts' , 'permission_callback' => function () { return current_user_can ( 'manage_options' ); }, ]); Now the endpoint has a clearer separation: Request ↓ Permission check ↓ Callback ↓ Data That separation becomes increasingly valuable as an API grows. Authentication Is Not Authorization These concepts are easy to m