Thạc sĩ CNTT. Nguyễn Bảo Quốc – Giảng viên FPT 0798.578.146 bquoc1190@gmail.com Phường Cẩm Lệ, Đà Nẵng

Lập trình PHP

Xây mini MVC bằng PHP: routing, controller, model, view

Tác giả: Nguyễn Bảo Quốc

Ảnh bìa bài viết: Xây mini MVC bằng PHP: routing, controller, model, view

Bài 9 trong lộ trình PHP, nối tiếp Composer và PSR-4. Tự xây một mini MVC giúp bạn hiểu framework như Laravel hay Symfony hoạt động bên trong. Yêu cầu PHP 8.0 trở lên.

Tóm tắt nhanh: Xây mini MVC bằng PHP: routing, controller, model, view

MVC là gì?

  • Model: làm việc với dữ liệu (cơ sở dữ liệu, quy tắc nghiệp vụ).
  • View: giao diện hiển thị cho người dùng.
  • Controller: nhận yêu cầu, gọi Model, chọn View để trả về.
quanly-sv/
├── public/
│   ├── index.php       # front controller
│   └── .htaccess
├── src/
│   ├── Router.php
│   ├── Controller/SinhVienController.php
│   └── Model/SinhVienModel.php
└── views/
    ├── layout.php
    └── sinh-vien/chi-tiet.php

Front controller và rewrite URL

Mọi yêu cầu đều đi qua public/index.php. Với Apache, dùng .htaccess chuyển hướng ngầm các URL không phải tệp thật:

# public/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Router

<?php
declare(strict_types=1);
namespace App;

final class Router
{
    /** @var array<string, array<int, array{0:string,1:callable|array}>> */
    private array $routes = [];

    public function get(string $path, callable|array $handler): void
    {
        $this->routes["GET"][] = [$path, $handler];
    }

    public function post(string $path, callable|array $handler): void
    {
        $this->routes["POST"][] = [$path, $handler];
    }

    public function dispatch(string $method, string $uri): void
    {
        $path = rtrim(parse_url($uri, PHP_URL_PATH) ?: "/", "/") ?: "/";

        foreach ($this->routes[$method] ?? [] as [$pattern, $handler]) {
            // {id} -> nhóm bắt có tên
            $regex = "#^" . preg_replace("#\{(\w+)\}#", "(?P<$1>[^/]+)", $pattern) . "$#";
            if (preg_match($regex, $path, $m)) {
                $params = array_filter($m, "is_string", ARRAY_FILTER_USE_KEY);
                if (is_array($handler)) {
                    [$class, $action] = $handler;
                    $handler = [new $class(), $action];
                }
                $handler(...$params);
                return;
            }
        }
        http_response_code(404);
        echo "404 - Không tìm thấy trang";
    }
}

Model, Controller và View

<?php
namespace App\Model;

final class SinhVienModel
{
    public function __construct(private \PDO $pdo) {}

    public function timTheoId(int $id): ?array
    {
        $st = $this->pdo->prepare("SELECT id, ho_ten, lop, diem_tb FROM sinh_vien WHERE id = ?");
        $st->execute([$id]);
        return $st->fetch() ?: null;
    }
}
<?php
namespace App\Controller;

use App\Model\SinhVienModel;

final class SinhVienController
{
    public function chiTiet(string $id): void
    {
        global $pdo; // đơn giản hóa cho bài học; thực tế nên dùng dependency injection
        $sv = (new SinhVienModel($pdo))->timTheoId((int) $id);

        if (!$sv) {
            http_response_code(404);
            echo "Không có sinh viên này";
            return;
        }
        view("sinh-vien/chi-tiet", ["sv" => $sv]);
    }
}
<?php
// hàm tiện ích (đặt trong src/helpers.php và nạp qua composer "files")
function e(?string $s): string
{
    return htmlspecialchars((string) $s, ENT_QUOTES, "UTF-8");
}

function view(string $file, array $data = []): void
{
    extract($data, EXTR_SKIP);
    require __DIR__ . "/../views/" . $file . ".php";
}

// views/sinh-vien/chi-tiet.php
// <h1><?= e($sv["ho_ten"]) ?></h1>
// <p>Lớp: <?= e($sv["lop"]) ?></p>

Gắn các thành phần lại

<?php
// public/index.php
declare(strict_types=1);
require __DIR__ . "/../vendor/autoload.php";

$pdo = require __DIR__ . "/../src/db.php";

$router = new App\Router();
$router->get("/", fn () => print("Trang chủ"));
$router->get("/sinh-vien/{id}", [App\Controller\SinhVienController::class, "chiTiet"]);
$router->dispatch($_SERVER["REQUEST_METHOD"], $_SERVER["REQUEST_URI"]);

Chạy thử không cần Apache bằng máy chủ tích hợp: php -S localhost:8000 -t public public/index.php, rồi mở http://localhost:8000/sinh-vien/1.

Bước tiếp theo để hoàn thiện

  • Thêm middleware kiểm tra đăng nhập và CSRF cho các route POST.
  • Tách cấu hình, thêm lớp Request và Response.
  • Dùng container dependency injection thay cho global.
  • Khi dự án lớn, cân nhắc chuyển sang framework như Laravel hoặc Symfony; bạn đã hiểu nguyên lý bên trong.

Bài tập

  1. Thêm route GET /sinh-vien hiển thị danh sách có phân trang, xem CRUD và phân trang.
  2. Thêm route POST /sinh-vien để thêm mới, kèm kiểm tra CSRF.
  3. Thêm trang 404 đẹp dùng chung layout.

Điểm cần nhớ

Cần xây dựng website hoặc hệ thống bằng PHP? Xem dịch vụ phát triển phần mềm hoặc chương trình lập trình cho sinh viên, hoặc liên hệ tư vấn.

Đọc tiếp trong lộ trình

Chia sẻ: Facebook X LinkedIn

1 bình luận

Để lại bình luận

Your email address will not be published. Required fields are marked *