惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Security Latest
Security Latest
P
Proofpoint News Feed
GbyAI
GbyAI
PCI Perspectives
PCI Perspectives
博客园 - Franky
N
Netflix TechBlog - Medium
博客园_首页
WordPress大学
WordPress大学
K
Kaspersky official blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
T
Threatpost
The Hacker News
The Hacker News
H
Help Net Security
S
Securelist
Recent Announcements
Recent Announcements
腾讯CDC
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta
C
Cisco Blogs
V
V2EX
C
Check Point Blog
S
Schneier on Security
Cyberwarzone
Cyberwarzone
C
Cybersecurity and Infrastructure Security Agency CISA
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
博客园 - 叶小钗
A
Arctic Wolf
AWS News Blog
AWS News Blog
Latest news
Latest news
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
B
Blog
aimingoo的专栏
aimingoo的专栏
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything BFF模式详解:构建前后端协同的中间层 I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
PHP 8.4 Asymmetric Visibility: 5 Patterns That Replace Constructors and Setters
Gabriel Anha · 2026-05-24 · via DEV Community

PHP 8.4 shipped asymmetric visibility in November 2024, and most teams that picked it up used it for exactly one thing: skipping the getter. That's the obvious case. There are four better ones.

The feature is small. The syntax is public public(set), public protected(set), public private(set) and the symmetric variants. The read modifier sits where it always did. The write modifier goes in parentheses next to set. That's the whole thing.

What it replaces is bigger. It replaces the private-property-plus-public-getter pattern PHP teams have written for fifteen years. It replaces a chunk of constructor boilerplate. Paired with property hooks and readonly, it replaces the inner builder pattern. Let's go through it.

What public(set) actually changes

Here's an Order class in PHP 8.3. Status changes from inside the domain, total changes after items are recalculated, but both fields are read from anywhere: templates, serializers, controllers.

// PHP 8.3, the old way
final class Order
{
    private OrderStatus $status;
    private Money $total;

    public function __construct(
        private readonly OrderId $id,
        OrderStatus $status,
        Money $total,
    ) {
        $this->status = $status;
        $this->total = $total;
    }

    public function getId(): OrderId
    {
        return $this->id;
    }

    public function getStatus(): OrderStatus
    {
        return $this->status;
    }

    public function getTotal(): Money
    {
        return $this->total;
    }

    public function markPaid(): void
    {
        $this->status = OrderStatus::Paid;
    }
}

Enter fullscreen mode Exit fullscreen mode

Three getters that do nothing. A constructor that exists only to assign. The same shape in PHP 8.4:

// PHP 8.4, same semantics, one third the code
final class Order
{
    public function __construct(
        public readonly OrderId $id,
        public private(set) OrderStatus $status,
        public private(set) Money $total,
    ) {}

    public function markPaid(): void
    {
        $this->status = OrderStatus::Paid;
    }
}

Enter fullscreen mode Exit fullscreen mode

The read surface is unchanged. $order->status works from a Twig template the same way $order->getStatus() did. The write surface is now scoped to the class itself. A controller cannot do $order->status = OrderStatus::Refunded. It'll get Cannot modify private(set) property Order::$status from global scope.

That's the headline. Now the patterns.

Pattern 1: Read-anywhere, write-from-domain

This is the obvious case, and the one most blog posts stop at. You want a property that any caller can read but only the owning aggregate can mutate. Before 8.4, you wrote a getter and a private field. Now you write the field once.

final class EmailAddress
{
    public public(set) string $value {
        set (string $value) {
            if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                throw new InvalidArgumentException(
                    "Invalid email: {$value}"
                );
            }
            $this->value = strtolower($value);
        }
    }

    public function __construct(string $value)
    {
        $this->value = $value;
    }
}

Enter fullscreen mode Exit fullscreen mode

public public(set) is the loud one: readable and writable from everywhere. Pair it with a property hook (the other big PHP 8.4 feature) and you get validation on every assignment, including the one inside the constructor. That EmailAddress class is now a value object with five lines of business logic and zero getter-setter ceremony.

Worth noting: the hook fires on the constructor assignment too. If you ever want to bypass it, you can't from inside the constructor without changing the property declaration. That's a feature, not a bug. Your invariants hold from the moment the object exists.

Pattern 2: Builder objects without the builder

The builder pattern in PHP got cleaned up by readonly in 8.2 and by clone-with semantics in 8.4. Asymmetric visibility is the last piece. You can write a fluent immutable object without a separate OrderBuilder class.

final class Order
{
    public function __construct(
        public readonly OrderId $id,
        public private(set) OrderStatus $status = OrderStatus::Draft,
        public private(set) ?Address $shippingAddress = null,
        public private(set) array $items = [],
    ) {}

    public function withShippingAddress(Address $address): self
    {
        $clone = clone $this;
        $clone->shippingAddress = $address;
        return $clone;
    }

    public function withItem(OrderItem $item): self
    {
        $clone = clone $this;
        $clone->items = [...$this->items, $item];
        return $clone;
    }
}

Enter fullscreen mode Exit fullscreen mode

private(set) means the property is writable from inside the class, including from inside a clone of the class. So $clone->shippingAddress = $address works because we're still inside Order when we run it. Outside callers can read every field. Outside callers cannot mutate.

This is the part that makes builder classes obsolete for most cases. The builder existed to hold the half-built state separately from the final object. With clone-on-write and private(set), you can hold both states in the same class without leaking mutability to the world.

Pattern 3: Aggregate-root field guards

In domain-driven design you've got aggregate roots that own a chunk of state and enforce invariants over it. The Order owns its line items. Nobody outside the aggregate gets to mess with the items array directly. Before 8.4, this meant private array $items plus public function getItems(): array { return $this->items; } plus a defensive copy if you cared about callers mutating the returned array.

Asymmetric visibility plus a property hook makes the guard explicit and short:

final class Order
{
    public function __construct(
        public readonly OrderId $id,
        public private(set) Money $total = new Money(0, 'EUR'),
        public private(set) array $items = [],
    ) {}

    public function addItem(OrderItem $item): void
    {
        if ($this->status !== OrderStatus::Draft) {
            throw new DomainException(
                "Cannot add items to a {$this->status->value} order"
            );
        }
        $this->items[] = $item;
        $this->recalculateTotal();
    }

    private function recalculateTotal(): void
    {
        $this->total = array_reduce(
            $this->items,
            fn(Money $sum, OrderItem $i) => $sum->add($i->subtotal()),
            new Money(0, 'EUR'),
        );
    }

    public public(set) OrderStatus $status = OrderStatus::Draft {
        set (OrderStatus $next) {
            if (!$this->status->canTransitionTo($next)) {
                throw new DomainException(
                    "Cannot move from {$this->status->value} to {$next->value}"
                );
            }
            $this->status = $next;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Two things to notice. First, $this->items[]= $item works from inside addItem() because we're inside the class. Second, the status property uses public public(set) plus a hook, meaning anyone can assign to it, but the hook runs the transition guard. That's the right shape when you want external callers to drive transitions (a workflow engine, a controller after authorization) but you still want the domain to reject illegal moves.

The combination of public(set) plus property hook is asymmetric visibility's best partner.

Pattern 4: DTO inputs with selective immutability

DTOs are the case where people overuse readonly class and then can't deserialize them. You want most fields locked after construction. You want one or two to be settable by infrastructure (a request ID set by middleware, a correlation ID injected by an event bus). Asymmetric visibility maps to this perfectly.

final class CreateOrderCommand
{
    public function __construct(
        public readonly CustomerId $customerId,
        public readonly array $items,
        public readonly Address $shippingAddress,
        public public(set) ?string $correlationId = null,
        public public(set) ?string $idempotencyKey = null,
    ) {}
}

Enter fullscreen mode Exit fullscreen mode

Three fields are truly immutable. Two fields are open for write. Anyone can set them, but the values flow from infrastructure, not the user. The command is still a value-ish object. The framework can inject what it needs without you writing a setter.

public(set) on the open fields means no scoping rules. If you want to lock them to a specific layer, switch to protected(set) and require the framework integration to extend the DTO. I'd avoid that. It's clever, and clever is a smell in DTOs.

Pattern 5: Where it breaks: serialization, Eloquent casting, Doctrine hydration

The pattern is great. The infrastructure around it isn't, yet.

Symfony Serializer (6.4 and 7.x) handles asymmetric visibility correctly for deserialization because it uses reflection and respects property scope when writing. So $serializer->deserialize($json, Order::class, 'json') works fine, because the serializer is privileged enough to write private(set) fields. Newer point releases handle it cleanly.

Eloquent attribute casting (Laravel 11.x and 12.x) is the case that bites integration code. Eloquent assigns properties via __set() on the model, not on the value object. If you've got a custom cast that produces an asymmetric-visibility value object, the cast itself works. But if you write the cast's set() method to mutate an existing instance, you'll hit Cannot modify private(set) property. The fix is to always return a new instance from CastsAttributes::set(), never mutate. That's good practice anyway; PHP 8.4 just makes you do it.

Doctrine ORM (3.x) hydrates entities via reflection, so private and private(set) properties hydrate fine. The trap is Doctrine's change-tracking. When you mutate a tracked entity via a method, Doctrine sees the change. When you clone it (Pattern 2 above), Doctrine treats the clone as detached. Don't mix the clone-with-readonly pattern with Doctrine-managed entities; the framework expects mutability on its managed objects.

JMS Serializer (still common in Symfony shops) had no support at 3.31. It assigns through public scope, which breaks private(set). Either upgrade to Symfony Serializer or write a custom handler.

The gotcha: protected(set) plus inheritance plus constructor promotion

This is the one undocumented edge case. Constructor-promoted properties with protected(set) look fine at definition. They get weird at extension.

class Money
{
    public function __construct(
        public protected(set) int $amount,
        public readonly string $currency,
    ) {}
}

class TaxableMoney extends Money
{
    public function withTax(float $rate): self
    {
        $clone = clone $this;
        $clone->amount = (int) ($this->amount * (1 + $rate));
        return $clone;
    }
}

Enter fullscreen mode Exit fullscreen mode

That works. The child class is inside the protected(set) scope so the assignment is legal. The catch: if a third-party library extends your class and tries to mutate amount through a method on its own subclass, it'll work too. protected(set) is wider than people assume. It's the equivalent of writing a protected function setAmount() in 8.3, which means any subclass anywhere is part of your write surface.

If you want true immutability after construction, use public private(set). If you want a hierarchy where children mutate, use public protected(set) and document that the subclass tree is part of your write contract.

When NOT to use it

Not every short-lived object needs asymmetric visibility. A request DTO that lives for one HTTP call, gets validated, gets handed to a use case, and gets garbage-collected doesn't need private(set). The cognitive cost of the modifier is real. The runtime cost is zero, but the cost of someone reading your code and wondering why you bothered isn't.

The shape I'd recommend:

  • Aggregate roots and entities with invariants: yes.
  • Value objects that ship across boundaries: yes, paired with readonly or with hooks.
  • Internal DTOs that live for one request: no, public readonly or plain public is enough.
  • Library code with a public API: yes, for any field where the contract is "callers read, library writes."
  • Models managed by an ORM: only with the caveats above.

PHP 8.4's asymmetric visibility isn't a revolution. It's the missing piece that lets you stop writing getter classes and start writing real objects. Five-year-old codebases full of private $foo plus public function getFoo() are exactly the codebases that should run Rector against the relevant rule and reclaim a thousand lines of nothing.

Which of these five patterns is the first one you'd reach for in your codebase, and which property would you rewrite first?


If this was useful

Asymmetric visibility is the kind of language feature that nudges you toward smaller, more honest objects, the kind of objects that survive a framework swap. That's the architectural layer the book covers: how to build PHP applications that outlive Laravel, Symfony, or whichever framework you're on this year. If the patterns in this post resonated, Decoupled PHP is the longer-form version, with chapters on aggregates, value objects, and the boundary between domain code and framework code.

Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework

Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.