Skip to main content

Lesson 7 of 7

Mini Project: Blog System - Part 6 (Database-Backed Posts)

Replace the hardcoded post array with a real MySQL database. Implement the full PdoPostRepository against the Blog System schema - create, read, paginate with JOIN for author names, update, delete - wired into the PostService and front-controller router.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Blog Part 6 - PDO Repository & Wiring

Blog Part 6 - PDO Repository & Wiring
<?php
declare(strict_types=1);

// src/Infrastructure/Repository/PdoPostRepository.php
namespace App\Infrastructure\Repository;

use App\Blog\Domain\{Post, PostStatus, Author, Email};
use App\Blog\Repository\PostRepositoryInterface;
use PDO;

class PdoPostRepository implements PostRepositoryInterface {
    public function __construct(private readonly PDO $pdo) {}

    public function findById(int $id): ?Post {
        $stmt = $this->pdo->prepare(
            "SELECT p.*, u.name AS author_name, u.email AS author_email
             FROM posts p JOIN users u ON u.id = p.author_id
             WHERE p.id = :id LIMIT 1"
        );
        $stmt->execute([":id" => $id]);
        $row = $stmt->fetch();
        return $row ? $this->hydrate($row) : null;
    }

    public function findAllPublished(int $limit = 20, int $offset = 0): array {
        $stmt = $this->pdo->prepare(
            "SELECT p.id, p.title, p.slug, p.status, p.published_at,
                    u.name AS author_name, u.email AS author_email
             FROM posts p JOIN users u ON u.id = p.author_id
             WHERE p.status = 'published'
             ORDER BY p.published_at DESC
             LIMIT :limit OFFSET :offset"
        );
        $stmt->bindValue(":limit",  $limit,  PDO::PARAM_INT);
        $stmt->bindValue(":offset", $offset, PDO::PARAM_INT);
        $stmt->execute();
        return array_map([$this, "hydrate"], $stmt->fetchAll());
    }

    public function save(Post $post): Post {
        if ($post->id === 0) {
            // INSERT
            $stmt = $this->pdo->prepare(
                "INSERT INTO posts (title, slug, body, status, author_id, published_at, created_at)
                 VALUES (:title, :slug, :body, :status, :author_id, :published_at, UTC_TIMESTAMP())"
            );
        } else {
            // UPDATE
            $stmt = $this->pdo->prepare(
                "UPDATE posts SET title=:title, slug=:slug, body=:body, status=:status,
                 published_at=:published_at, updated_at=UTC_TIMESTAMP()
                 WHERE id=:id"
            );
            $stmt->bindValue(":id", $post->id, PDO::PARAM_INT);
        }

        $data = $post->toArray();
        $stmt->execute([
            ":title"        => $data["title"],
            ":slug"         => $data["slug"],
            ":body"         => $data["body"],
            ":status"       => $data["status"],
            ":author_id"    => $data["author_id"] ?? 1,
            ":published_at" => $data["published_at"],
        ]);

        return $post->id === 0
            ? $post->withId((int) $this->pdo->lastInsertId())
            : $post;
    }

    public function delete(int $id): bool {
        $stmt = $this->pdo->prepare("DELETE FROM posts WHERE id = :id");
        $stmt->execute([":id" => $id]);
        return $stmt->rowCount() > 0;
    }

    private function hydrate(array $row): Post {
        return new Post(
            id:     (int) $row["id"],
            title:  $row["title"],
            slug:   $row["slug"],
            body:   $row["body"] ?? "",
            status: PostStatus::from($row["status"]),
            author: new Author($row["author_name"], new Email($row["author_email"])),
        );
    }
}

Quick Quiz

Module Quiz

Module Quiz
Question 1 of 5

Why should PDO::ATTR_EMULATE_PREPARES be set to false?

Tip

Tip

Practice Mini Project Blog System Part 6 DatabaseBacked Posts 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 6 (Database-Backed Posts)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Blog System Part 6 DatabaseBacked Posts 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 6 DatabaseBacked Posts 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