Skip to main content
Understanding Object-Oriented Design in PHP
  1. Blog Posts/

🧰 Understanding Object-Oriented Design in PHP

2 min read·
oop php laravel

Published on: 2022-03-30

Object-oriented programming (OOP) is at the heart of most modern PHP applications — from Laravel apps to custom frameworks. But visualizing class structures and relationships can get messy fast.

Let’s break down a classic OOP pattern using class diagrams.


🧩 Use Case: A Simple Blog System

We’ll model a basic blog system with:

  • A User who can write Posts
  • A Post that can have multiple Comments
  • A Comment that belongs to both a User and a Post

Here’s what the class diagram looks like:


🛠 PHP Implementation (Simplified)

class User {
  public int $id;
  public string $name;
  public string $email;

  public function writePost(string $title, string $body): Post {
    return new Post($title, $body, $this);
  }

  public function addComment(Post $post, string $content): Comment {
    return new Comment($content, $this, $post);
  }
}

class Post {
  public int $id;
  public string $title;
  public string $body;
  public User $author;
  public array $comments = [];

  public function __construct(string $title, string $body, User $author) {
    $this->title = $title;
    $this->body = $body;
    $this->author = $author;
  }

  public function addComment(Comment $comment): void {
    $this->comments[] = $comment;
  }
}

class Comment {
  public int $id;
  public string $content;
  public User $author;
  public Post $post;

  public function __construct(string $content, User $author, Post $post) {
    $this->content = $content;
    $this->author = $author;
    $this->post = $post;
  }
}

💡 Why This Is Useful

When your project grows, a Mermaid class diagram like this:

  • Helps onboard teammates faster
  • Clarifies relationships (like “has-many”, “belongs-to”)
  • Aids in planning refactors or new features

🧠 TL;DR

  • Mermaid class diagrams are a lightweight, Markdown-friendly way to visualize OOP
  • PHP makes class relationships easy to express
  • This structure can be extended for likes, tags, categories, and more