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

推荐订阅源

S
Schneier on Security
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Project Zero
Project Zero
T
The Exploit Database - CXSecurity.com
G
GRAHAM CLULEY
T
Threatpost
A
Arctic Wolf
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Scott Helme
Scott Helme
Simon Willison's Weblog
Simon Willison's Weblog
P
Proofpoint News Feed
C
Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
Kaspersky official blog
P
Palo Alto Networks Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threat Research - Cisco Blogs
The Hacker News
The Hacker News
T
Tor Project blog
NISL@THU
NISL@THU
The GitHub Blog
The GitHub Blog
Security Latest
Security Latest
aimingoo的专栏
aimingoo的专栏
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
Martin Fowler
Martin Fowler
N
News | PayPal Newsroom
P
Privacy & Cybersecurity Law Blog
MyScale Blog
MyScale Blog
G
Google Developers Blog
V
V2EX
V
Visual Studio Blog
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
L
LINUX DO - 热门话题
MongoDB | Blog
MongoDB | Blog
腾讯CDC
J
Java Code Geeks
The Last Watchdog
The Last Watchdog
L
Lohrmann on Cybersecurity
Cyberwarzone
Cyberwarzone
博客园 - 聂微东
Webroot Blog
Webroot Blog
S
Secure Thoughts

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 Updated: BFF Pattern 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
OOP - Make Your Code More Scalable
MD Hemal Akhand · 2026-06-14 · via DEV Community

Have you ever opened a Project and found one giant PHP file with 2,000 lines?

Functions everywhere. Global variables. No clear structure. And every time you add a feature, something else breaks.

You are not alone.

Most developers know what a class is. Far fewer know how to design classes that stay clean as a project grows.

There is a real difference between:

  • Using OOP syntax — writing class MyPlugin { }
  • Thinking in OOP design — knowing when to split, inject, and abstract

This post closes that gap.


TL;DR — what you will learn

  • Method chaining — chain calls on one line by returning $this
  • Dependency injection — pass objects in from outside; stop hiding new inside business logic
  • SRP — one class, one reason to change
  • OCP — extend with new classes, do not rewrite stable code
  • LSP — subtypes must be swappable without breaking callers
  • ISP — small interfaces; no forced empty methods
  • DIP — high-level code depends on interfaces, not concrete classes

No Laravel required. No framework magic. Just PHP that fits inside WordPress.


Why OOP matters in WordPress

WordPress grew up procedural. Functions in the global namespace. Hooks everywhere. That still works — and for small plugins, it is often the right choice.

But when a plugin grows, procedural code tends to:

  • Mix business logic with WordPress hooks in the same function
  • Repeat database calls because nothing is shared cleanly
  • Break in unexpected places when you change one feature

Object-oriented design does not replace WordPress hooks. It organizes what happens inside those hooks.

The goal is simple:

  • Each class does one job
  • Dependencies are passed in, not hidden inside
  • New features are added by extending — not by rewriting the same file

That is what we build toward in this guide.


Part 1: Method chaining

What is it?

Method chaining means every setter (and sometimes getter) returns $this — the same object — so you can call the next method immediately on one line.

It reads like a sentence instead of a list of separate steps.

Without chaining:

$student = new Student("Alex Rivera", 22, 101);
$student->setName("Jordan Lee");
$student->setAge(24);
$student->displayName();
$student->displaySeparator();
$student->displayRoll();

With chaining:

$student = new Student("Alex Rivera", 22, 101);
$student->setName("Jordan Lee")
        ->setAge(24)
        ->displayName()
        ->displaySeparator()
        ->displayRoll()
        ->displaySeparator()
        ->displayAge();
// Output: Jordan Lee, 101, 24

The secret: return $this

class Student {
    private $name, $age, $roll;

    public function setName($name) {
        $this->name = $name;
        return $this;   // ← enables chaining
    }

    public function setAge($age) {
        $this->age = $age;
        return $this;
    }

    public function displayName() {
        echo $this->name;
        return $this;
    }

    public function displaySeparator() {
        echo ", ";
        return $this;
    }
}

What is happening?

  1. Each method updates or displays a property
  2. Instead of returning nothing, each method returns $this
  3. PHP lets you call the next method on that returned object immediately

Why it matters in WordPress: Settings APIs, form builders, and custom query wrappers all read cleaner with chaining. Admin UI code becomes easier to scan.

Note: Chaining is a style choice, not a rule. Use it where readability improves.


Part 2: Dependency injection

What is it?

Instead of a class creating its own helper objects internally, you pass (inject) the object it needs from the outside.

Think of hiring a contractor. You do not build the plumbing yourself. You call a plumber and hand them the job.

Bad — tight coupling:

class StudentDisplay {
    public function show() {
        $student = new StudentRecord("Alex", 22, 101); // hard-coded inside
        $student->displayName();
    }
}

StudentDisplay is locked to StudentRecord. You cannot swap it for a database-backed student or a test fake without rewriting the class.

Good — dependency injection:

interface StudentData {
    public function displayName();
    public function displayAge();
}

class StudentRecord implements StudentData {
    private $name, $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function displayName() {
        echo "Student Name: " . $this->name;
    }

    public function displayAge() {
        echo "Student Age: " . $this->age;
    }
}

class StudentDisplay {
    public function show(StudentData $student) {
        $student->displayName();
        echo "<br/>";
        $student->displayAge();
    }
}

// Object created outside, passed in:
$student = new StudentRecord("Alex Rivera", 22);
$display = new StudentDisplay();
$display->show($student);

What is happening?

  1. StudentData is an interface — a contract
  2. StudentRecord implements that contract
  3. StudentDisplay only knows the interface, not the concrete class
  4. You create the student outside and pass it in — that pass is dependency injection

Two ways to inject:

Constructor injection (most common):

class OrderNotifier {
    private $mailer;

    public function __construct(MailerInterface $mailer) {
        $this->mailer = $mailer;
    }

    public function notify($order) {
        $this->mailer->send($order->getEmail(), "Order confirmed");
    }
}

Method injection (when dependency is only needed for one action):

class ReportGenerator {
    public function generate(ExporterInterface $exporter) {
        $exporter->export($this->buildReport());
    }
}

Why WordPress developers should care:

  • Testability — pass a fake mailer in tests instead of sending real emails
  • Flexibility — swap StudentRecord for DatabaseStudent without touching StudentDisplay
  • Cleaner plugins — AJAX handlers, admin screens, and repositories stay decoupled

Part 3: SOLID principles (all five)

SOLID is five design rules from Robert C. Martin (“Uncle Bob”). Together they answer one question:

How do I structure code so that adding features does not break everything?


S — Single Responsibility Principle (SRP)

Rule: A class should have only one reason to change.

Not “one method.” Not “small class.” One reason to change.

Bad — god class:

class SchoolSystem {
    public function countSchools() {}
    public function countTeachers() {}
    public function countStudents() {}
    public function sendParentEmails() {}
    public function syncToCRM() {}
}

Better — one class per responsibility:

interface CountableEntity {
    public function displayCount();
}

class SchoolCounter implements CountableEntity {
    public function displayCount() { echo "Schools: 30"; }
}

class TeacherCounter implements CountableEntity {
    public function displayCount() { echo "Teachers: 50"; }
}

class StudentCounter implements CountableEntity {
    public function displayCount() { echo "Students: 120"; }
}

class CountReporter {
    public function report(CountableEntity $entity) {
        $entity->displayCount();
    }
}

WordPress analogy: Do not put “save post meta,” “send notification email,” and “sync to CRM” in one hook callback. Split them into three classes.


O — Open/Closed Principle (OCP)

Rule: Open for extension, closed for modification.

Add new behavior by adding new classes — not by editing the same if/else block every sprint.

Without OCP:

function handleExam($role) {
    if ($role === 'teacher') {
        echo "Teacher manages exam";
    } elseif ($role === 'student') {
        echo "Student views exam";
    }
    // New role = edit this function again
}

With OCP:

interface ExamHandler {
    public function handleExam();
}

class TeacherExamHandler implements ExamHandler {
    public function handleExam() { echo "Teacher manages exam"; }
}

class StudentExamHandler implements ExamHandler {
    public function handleExam() { echo "Student views exam"; }
}

class ExamCoordinator {
    public function run(ExamHandler $handler) {
        $handler->handleExam();
    }
}
// New parent role? Add ParentExamHandler — never touch ExamCoordinator.

WordPress connection: Payment gateways, shipping methods, and export formats are classic OCP cases.


L — Liskov Substitution Principle (LSP)

Rule: If class B implements interface A, you must be able to swap B for any other implementation of A without breaking the program.

interface FeeManager {
    public function manageFees();
    public function manageCharges();
}

class School implements FeeManager {
    public function manageFees() { echo "School fee: $500"; }
    public function manageCharges() { echo "School exam charge: $60"; }
}

class Hospital implements FeeManager {
    public function manageFees() { echo "Hospital fee: $1,200"; }
    public function manageCharges() { echo "Lab charge: $80"; }
}

class BillingService {
    public function processFees(FeeManager $entity) {
        $entity->manageFees();
        echo "<br/>";
        $entity->manageCharges();
    }
}

$billing = new BillingService();
$billing->processFees(new School());    // works
$billing->processFees(new Hospital());  // also works

Warning sign: If a subclass overrides a method and throws “not supported” for half the callers, you probably violated LSP.


I — Interface Segregation Principle (ISP)

Rule: Do not force a class to implement methods it will never use.

Bad — fat interface:

interface OrganizationManager {
    public function studentCount();
    public function teacherCount();
    public function hospitalCount();
    public function doctorCount();
    public function universityRanking();
}

A school class would be forced to implement hospitalCount() — empty stub or fake data.

Better — segregated interfaces:

interface SchoolStats {
    public function studentCount();
    public function teacherAttendance();
    public function teacherCount();
}

interface HospitalStats {
    public function hospitalCount();
    public function doctorAttendance();
    public function doctorCount();
}

class SchoolDashboard implements SchoolStats {
    public function studentCount() { echo "Students: 120"; }
    public function teacherAttendance() { echo "Teacher attendance: 95%"; }
    public function teacherCount() { echo "Teachers: 30"; }
}

WordPress analogy: Split a 20-method PluginInterface into Activatable, SettingsPage, RestEndpoint — implement only what you need.


D — Dependency Inversion Principle (DIP)

Rule: High-level code should depend on abstractions (interfaces), not concrete classes.

Without DIP:

class AttendanceReport {
    public function run() {
        $teacher = new TeacherAttendance(); // locked to one class
        $teacher->record();
    }
}

With DIP:

interface AttendanceRecorder {
    public function record();
}

class TeacherAttendance implements AttendanceRecorder {
    public function record() { echo "Teacher attendance recorded"; }
}

class StudentAttendance implements AttendanceRecorder {
    public function record() { echo "Student attendance recorded"; }
}

class AttendanceReport {
    public function run(AttendanceRecorder $recorder) {
        $recorder->record();
    }
}

$report = new AttendanceReport();
$report->run(new StudentAttendance());

AttendanceReport never mentions TeacherAttendance or StudentAttendance by name. It only knows the AttendanceRecorder interface. That is dependency inversion.


Putting it all together

Idea One-line meaning
Method chaining Return $this to chain calls on one line
Dependency injection Pass objects in from outside the class
SRP One class, one reason to change
OCP Extend with new classes, do not modify stable code
LSP Subtypes must be swappable without breaking callers
ISP Small interfaces — no forced unused methods
DIP High-level code depends on interfaces, not concrete classes

You do not need all seven on day one.

Start here:

  • Week 1 → Split one god function into two classes (SRP)
  • Week 2 → Pass dependencies via constructor instead of new inside (DI + DIP)
  • Week 3 → Extract an interface before your next if/else role check (OCP)

Small steps. Big payoff over six months.


Common mistakes (and how to fix them)

  1. “I use classes, so I do OOP” — A 2,000-line Plugin_Main with 40 methods is still a god object. Split by responsibility.

  2. Editing the same file for every new feature — If every new payment method means editing checkout.php, apply OCP — add a class instead.

  3. Giant interfaces — If half your implementing classes have empty methods, apply ISP — break the interface apart.

  4. new ClassName() hidden inside business logic — If you cannot test without a real database, apply DI — inject a repository interface.

  5. Learning theory without writing code — Pick one hook in your plugin. Extract one class. Pass one dependency. That single refactor teaches more than reading ten articles.


From small plugin to scalable plugin

You do not need 50 classes on day one. A 200-line plugin with three focused classes is already a win.

As you grow, mature plugins typically add:

  • PSR-4 autoloading via Composer
  • Namespaces to avoid class name collisions
  • A thin bootstrap class that wires hooks on plugins_loaded
  • Interfaces for anything you might swap (mailer, storage, payment)
  • PHPUnit tests with mocked dependencies

The design thinking stays the same. Only the packaging gets more professional.


Final thoughts

Being an OOP developer is easy. Designing systems with clear responsibility boundaries is not.

The difference shows up six months later — when you add a feature and nothing else breaks. When a junior developer can read your class in five minutes. When you can write a test without booting all of WordPress.

Start small today:

  1. Pick one function in your plugin that does too much
  2. Extract one responsibility into its own class
  3. Pass its dependency through the constructor
  4. Define an interface if you might swap the implementation later

That is SRP, DI, and DIP in one afternoon.

Method chaining is the readable syntax. SOLID is the architecture underneath. WordPress hooks are still how you plug into the CMS.

You do not have to choose between “WordPress way” and “proper OOP.” You combine them.

That is how OOP stops being syntax and starts being design.