PHP โปรเจกต์: เว็บบล็อกเล็ก ๆ แบบ MVC เขียนมือ



MVC (Model–View–Controller) เป็นรูปแบบจัดโค้ดที่เฟรมเวิร์กทุกตัวใช้ โปรเจกต์นี้ทำเองจากศูนย์เพื่อให้เห็นว่าแต่ละส่วนรับผิดชอบอะไร

  • Model — ข้อมูลและกฎธุรกิจ (คุยกับ DB)
  • View — แสดงผล (HTML) ไม่มี logic
  • Controller — รับ request เรียก model เลือก view

หน้าที่มี

GET   /                    รายการโพสต์ (แบ่งหน้า)
GET   /posts/{id}          อ่านโพสต์
GET   /admin/posts/create  ฟอร์มเขียน (ต้องล็อกอิน — ใช้ Auth จากโปรเจกต์ 45)
POST  /admin/posts         บันทึกโพสต์

โครงสร้าง

blog/
├── public/index.php
├── src/
│   ├── Core/
│   │   ├── Router.php
│   │   ├── Controller.php     (base — มี view())
│   │   └── View.php
│   ├── Model/
│   │   └── Post.php
│   └── Controller/
│       ├── PostController.php
│       └── AdminPostController.php
├── templates/
│   ├── layout.php
│   ├── posts/index.php
│   ├── posts/show.php
│   └── admin/create.php
├── config/app.php
└── schema.sql

src/Core/View.php

<?php
declare(strict_types=1);

namespace App\Core;

final class View
{
    public function __construct(private string $path) {}

    /** @param array<string,mixed> $data */
    public function render(string $template, array $data = []): string
    {
        $e = static fn (mixed $v): string =>
            htmlspecialchars((string) $v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

        extract($data, EXTR_SKIP);
        ob_start();
        require "{$this->path}/{$template}.php";
        $content = ob_get_clean();

        // ครอบด้วย layout ถ้ามี $data['_layout'] !== false
        if (($data['_layout'] ?? true) !== false) {
            ob_start();
            require "{$this->path}/layout.php";
            return ob_get_clean();
        }
        return $content;
    }
}

view ทุกไฟล์มี $e() ไว้ escape — เรียก <?= $e($post->title) ?> ทุกที่

src/Core/Controller.php

<?php
declare(strict_types=1);

namespace App\Core;

use PDO;

abstract class Controller
{
    public function __construct(
        protected PDO $pdo,
        protected View $view,
    ) {}

    protected function render(string $template, array $data = []): string
    {
        return $this->view->render($template, $data);
    }

    protected function redirect(string $path): never
    {
        header("Location: $path");
        exit;
    }

    protected function notFound(): never
    {
        http_response_code(404);
        echo $this->view->render('errors/404', ['_layout' => true]);
        exit;
    }
}

src/Model/Post.php

<?php
declare(strict_types=1);

namespace App\Model;

use PDO;

final class Post
{
    public function __construct(
        public int $id,
        public string $title,
        public string $body,
        public string $createdAt,
    ) {}

    public static function fromRow(array $row): self
    {
        return new self(
            (int) $row['id'],
            $row['title'],
            $row['body'],
            $row['created_at'],
        );
    }

    public function excerpt(int $len = 120): string
    {
        return mb_substr($this->body, 0, $len)
            . (mb_strlen($this->body) > $len ? '…' : '');
    }
}

final class PostRepository
{
    private const PER_PAGE = 5;

    public function __construct(private PDO $pdo) {}

    /** @return array{items: list<Post>, page: int, totalPages: int} */
    public function paginate(int $page): array
    {
        $page = max(1, $page);
        $total = (int) $this->pdo
            ->query('SELECT COUNT(*) FROM posts WHERE published = 1')
            ->fetchColumn();

        $stmt = $this->pdo->prepare(
            'SELECT * FROM posts WHERE published = 1
             ORDER BY created_at DESC LIMIT :l OFFSET :o'
        );
        $stmt->bindValue(':l', self::PER_PAGE, PDO::PARAM_INT);
        $stmt->bindValue(':o', ($page - 1) * self::PER_PAGE, PDO::PARAM_INT);
        $stmt->execute();

        return [
            'items'      => array_map(Post::fromRow(...), $stmt->fetchAll()),
            'page'       => $page,
            'totalPages' => max(1, (int) ceil($total / self::PER_PAGE)),
        ];
    }

    public function find(int $id): ?Post
    {
        $stmt = $this->pdo->prepare('SELECT * FROM posts WHERE id = ? AND published = 1');
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        return $row ? Post::fromRow($row) : null;
    }

    public function create(string $title, string $body): int
    {
        $stmt = $this->pdo->prepare(
            'INSERT INTO posts (title, body, published) VALUES (?, ?, 1)'
        );
        $stmt->execute([$title, $body]);
        return (int) $this->pdo->lastInsertId();
    }
}

src/Controller/PostController.php

<?php
declare(strict_types=1);

namespace App\Controller;

use App\Core\Controller;
use App\Model\PostRepository;

final class PostController extends Controller
{
    public function index(array $params): string
    {
        $repo = new PostRepository($this->pdo);
        $data = $repo->paginate((int) ($_GET['page'] ?? 1));

        return $this->render('posts/index', $data);
    }

    public function show(array $params): string
    {
        $post = (new PostRepository($this->pdo))->find((int) $params['id']);
        if ($post === null) {
            $this->notFound();
        }
        return $this->render('posts/show', ['post' => $post]);
    }
}

src/Controller/AdminPostController.php

<?php
declare(strict_types=1);

namespace App\Controller;

use App\Core\Controller;
use App\Model\PostRepository;
use App\Support\Csrf;   // reuse จากโปรเจกต์ 45

final class AdminPostController extends Controller
{
    public function create(array $params): string
    {
        $this->requireAuth();
        return $this->render('admin/create', [
            'csrf'   => Csrf::field(),
            'errors' => [],
            'old'    => ['title' => '', 'body' => ''],
        ]);
    }

    public function store(array $params): string
    {
        $this->requireAuth();
        Csrf::check();

        $title = trim($_POST['title'] ?? '');
        $body  = trim($_POST['body'] ?? '');

        $errors = [];
        if ($title === '' || mb_strlen($title) > 200) {
            $errors['title'] = 'หัวข้อ 1–200 ตัวอักษร';
        }
        if ($body === '') {
            $errors['body'] = 'กรุณากรอกเนื้อหา';
        }

        if ($errors) {
            return $this->render('admin/create', [
                'csrf'   => Csrf::field(),
                'errors' => $errors,
                'old'    => compact('title', 'body'),
            ]);
        }

        $id = (new PostRepository($this->pdo))->create($title, $body);
        $this->redirect("/posts/$id");
    }

    private function requireAuth(): void
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect('/login');
        }
    }
}

public/index.php

<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use App\Core\{Router, View};

session_start();

$config = require __DIR__ . '/../config/app.php';

$pdo = new PDO(
    $config['db']['dsn'], $config['db']['user'], $config['db']['pass'],
    [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ],
);
$view = new View(__DIR__ . '/../templates');

$router = new Router();
$router->get('/',                       [App\Controller\PostController::class, 'index']);
$router->get('/posts/{id}',             [App\Controller\PostController::class, 'show']);
$router->get('/admin/posts/create',     [App\Controller\AdminPostController::class, 'create']);
$router->post('/admin/posts',           [App\Controller\AdminPostController::class, 'store']);

echo $router->dispatch(
    $_SERVER['REQUEST_METHOD'],
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),
    deps: [$pdo, $view],
);

Router (src/Core/Router.php) คล้ายบทที่ 43 — จับ {id} เป็น named group แล้ว new $class(...$deps) ก่อนเรียก action

templates/posts/index.php

<h1>บทความล่าสุด</h1>

<?php foreach ($items as $post): ?>
    <article>
        <h2><a href="/posts/<?= $post->id ?>"><?= $e($post->title) ?></a></h2>
        <time><?= $e($post->createdAt) ?></time>
        <p><?= $e($post->excerpt()) ?></p>
    </article>
<?php endforeach; ?>

<nav>
    <?php if ($page > 1): ?>
        <a href="/?page=<?= $page - 1 ?>">← ก่อนหน้า</a>
    <?php endif; ?>
    หน้า <?= $page ?>/<?= $totalPages ?>
    <?php if ($page < $totalPages): ?>
        <a href="/?page=<?= $page + 1 ?>">ถัดไป →</a>
    <?php endif; ?>
</nav>

posts/show.php แสดงเนื้อหา — ถ้าเก็บเป็น plain text ใช้ <?= nl2br($e($post->body)) ?> (escape ก่อน แล้วค่อยแปลง newline)

รัน

php -S localhost:8000 -t public
  • / — เห็นรายการโพสต์ กด pagination ได้
  • /posts/1 — อ่านโพสต์, /posts/999 — หน้า 404
  • /admin/posts/create — เด้งไป /login ถ้ายังไม่ล็อกอิน
  • ล็อกอินแล้วเขียนโพสต์ → validate → บันทึก → redirect ไปหน้าโพสต์

ทำไมแยก MVC

  • แก้ที่เดียว — เปลี่ยน SQL อยู่ใน Model, เปลี่ยนหน้าตาอยู่ใน View, เปลี่ยน flow อยู่ใน Controller
  • ทดสอบได้ — PostRepository เทสต์ด้วย sqlite::memory:, ไม่ต้องเปิดเบราว์เซอร์
  • reuse — PostRepository::paginate() ใช้ได้ทั้งหน้าเว็บและ API
  • นี่คือสิ่งที่ Laravel/Symfony ทำ — เข้าใจอันนี้แล้วเรียนเฟรมเวิร์กเร็วขึ้นมาก

เรื่องที่คนมักพลาด

  • ใส่ SQL ใน Controller หรือ View — พอ query ซ้ำในหลายหน้า แก้ไม่ทั่ว ย้ายไป Model
  • ใส่ logic ใน View (คำนวณ, เงื่อนไขซับซ้อน) — View ควรแค่วน+แสดง เตรียมข้อมูลให้เสร็จใน Controller/Model
  • View ไม่ escape — <?= $post->body ?> ตรง ๆ = stored XSS ใช้ $e() ทุกจุด (หรือย้ายไป Twig ที่ escape เอง)
  • nl2br() ก่อน htmlspecialchars() — <br> ที่ nl2br ใส่จะโดน escape กลายเป็นข้อความ ทำ escape ก่อน
  • Controller ทำงานหนักเอง — Controller ควรบาง: รับ input, เรียก model, เลือก view งานหนักอยู่ใน Model/service
  • สร้าง new PostRepository($this->pdo) ซ้ำในทุก action — โอเคสำหรับโปรเจกต์เล็ก โปรเจกต์ใหญ่ใช้ DI container ฉีดให้

สรุป

  • Model (Post, PostRepository) — ข้อมูล + SQL + กฎธุรกิจ, คืนอ็อบเจกต์ไม่ใช่ array ดิบ
  • View (templates/*.php) — HTML ล้วน, $e() ทุกค่า, ไม่มี logic
  • Controller — รับ request → เรียก Model → render() view หรือ redirect() บาง ๆ
  • front controller + Router ต่อทุกอย่างเข้าด้วยกัน
  • แยกแบบนี้ = แก้ที่เดียว, เทสต์ได้, และเป็นพื้นฐานของเฟรมเวิร์กจริง

บทสุดท้าย โปรเจกต์เครื่องมือ CLI — ดึงข้อมูลจาก API ด้วย cURL, ประมวลผล, และเขียนรายงาน CSV