Skip to main content

Lesson 7 of 7

Mini Project: Blog System - Part 4 (OOP Models)

Refactor the Blog System from procedural arrays to a proper OOP model layer. Introduce the Post, User, and Author Value Objects with constructor promotion, immutable withers, and typed methods that replace procedural array access throughout the application.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Blog Part 4 - OOP Domain Layer

Blog Part 4 - OOP Domain Layer
<?php
declare(strict_types=1);

// ── src/Domain/Author.php - Value Object ─────────────────────
final class Author {
    public function __construct(
        public readonly string $name,
        public readonly Email  $email,
    ) {
        if (mb_strlen(trim($name)) < 2) {
            throw new InvalidArgumentException("Author name too short.");
        }
    }

    public function __toString(): string { return $this->name; }
}

// ── src/Domain/Post.php - Rich Domain Entity ─────────────────
final class Post {
    private static int $nextId = 1;

    public readonly int               $id;
    public readonly DateTimeImmutable $createdAt;

    public function __construct(
        public readonly string $title,
        public readonly string $slug,
        public readonly string $body,
        public readonly Author $author,
        private bool           $published    = false,
        private ?DateTimeImmutable $publishedAt = null,
        private array          $tags         = [],
        ?int                   $id           = null,
        ?DateTimeImmutable     $createdAt    = null,
    ) {
        $this->id        = $id ?? self::$nextId++;
        $this->createdAt = $createdAt ?? new DateTimeImmutable("now", new DateTimeZone("UTC"));
    }

    public static function fromArray(array $data): static {
        return new static(
            title:     $data["title"],
            slug:      $data["slug"],
            body:      $data["body"],
            author:    new Author($data["author_name"], new Email($data["author_email"])),
            published: (bool) $data["published"],
            tags:      $data["tags"] ?? [],
            id:        $data["id"] ?? null,
        );
    }

    public function publish(): static {
        if ($this->published) throw new RuntimeException("Post already published.");
        $clone = clone $this;
        $clone->published   = true;
        $clone->publishedAt = new DateTimeImmutable("now", new DateTimeZone("UTC"));
        return $clone;
    }

    public function addTag(string $tag): static {
        $tag = strtolower(trim($tag));
        if (in_array($tag, $this->tags, true)) return $this;
        $clone       = clone $this;
        $clone->tags = [...$this->tags, $tag];
        return $clone;
    }

    public function isPublished(): bool     { return $this->published; }
    public function getPublishedAt(): ?DateTimeImmutable { return $this->publishedAt; }
    public function getTags(): array        { return $this->tags; }
    public function hasTag(string $tag): bool {
        return in_array(strtolower($tag), $this->tags, true);
    }

    public function toArray(): array {
        return [
            "id"           => $this->id,
            "title"        => $this->title,
            "slug"         => $this->slug,
            "body"         => $this->body,
            "author_name"  => $this->author->name,
            "author_email" => (string) $this->author->email,
            "published"    => $this->published,
            "published_at" => $this->publishedAt?->format("c"),
            "tags"         => $this->tags,
            "created_at"   => $this->createdAt->format("c"),
        ];
    }
}

// ── Usage ─────────────────────────────────────────────────────
$author = new Author("Alice Johnson", new Email("alice@example.com"));
$post   = new Post("PHP OOP Deep Dive", "php-oop", "OOP is great...", $author, tags: ["php","oop"]);

$published = $post->publish()->addTag("tutorial");

echo $published->isPublished() ? "Published" : "Draft";  // Published
echo json_encode($published->toArray(), JSON_PRETTY_PRINT);

Quick Quiz

Module Quiz

Module Quiz
Question 1 of 5

What is PHP 8.0 constructor property promotion?

Tip

Tip

Practice Mini Project Blog System Part 4 OOP Models in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Blog System - Part 4 (OOP Models)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Blog System Part 4 OOP Models from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Mini Project Blog System Part 4 OOP Models is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done