萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 物件導向日曆類實作:支援月份切換、年份選擇與今日高亮

這篇文章展示如何使用 PHP 物件導向方式建立一個功能完整的日曆元件,支援上下月/年切換、下拉選單快速跳轉、今日高亮顯示,並分離 HTML 模板與邏輯,便於維護擴充。

Calendar 類別核心程式碼 (calendar.class.php)

<?php
class Calendar {
    private $year;
    private $month;
    private $startWeekday; // 該月 1 號是星期幾 (0=日)
    private $daysInMonth;  // 該月總天數

    public function __construct() {
        // 從 GET 參數取得年月,預設為當前
        $this->year  = isset($_GET['year'])  ? (int)$_GET['year']  : (int)date('Y');
        $this->month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');

        // 修正邊界
        $this->year  = max(1970, min(2100, $this->year));
        $this->month = max(1, min(12, $this->month));

        $this->startWeekday = (int)date('w', mktime(0, 0, 0, $this->month, 1, $this->year));
        $this->daysInMonth  = (int)date('t', mktime(0, 0, 0, $this->month, 1, $this->year));
    }

    public function render($targetUrl = 'test.php') {
        echo '<table class="calendar">';
        $this->renderHeader($targetUrl);
        $this->renderWeekdays();
        $this->renderDays();
        echo '</table>';
    }

    private function renderHeader($url) {
        echo '<tr>';
        echo '<td><a href="?' . $this->prevYear() . '">«</a></td>';
        echo '<td><a href="?' . $this->prevMonth() . '">‹</a></td>';
        echo '<td colspan="3">';
        echo '<form method="get" action="' . htmlspecialchars($url) . '">';
        echo '<select name="year" onchange="this.form.submit()">';
        for ($y = 1970; $y <= 2100; $y++) {
            $sel = ($y === $this->year) ? ' selected' : '';
            echo "<option value=\"$y\"$sel>$y</option>";
        }
        echo '</select>';
        echo '<select name="month" onchange="this.form.submit()">';
        for ($m = 1; $m <= 12; $m++) {
            $sel = ($m === $this->month) ? ' selected' : '';
            echo "<option value=\"$m\"$sel>$m</option>";
        }
        echo '</select>';
        echo '</form>';
        echo '</td>';
        echo '<td><a href="?' . $this->nextMonth() . '">›</a></td>';
        echo '<td><a href="?' . $this->nextYear() . '">»</a></td>';
        echo '</tr>';
    }

    private function renderWeekdays() {
        $weeks = ['日','一','二','三','四','五','六'];
        echo '<tr>';
        foreach ($weeks as $w) {
            echo "<th>$w</th>";
        }
        echo '</tr>';
    }

    private function renderDays() {
        echo '<tr>';
        // 1號前的空格
        for ($i = 0; $i < $this->startWeekday; $i++) {
            echo '<td>&nbsp;</td>';
        }

        $cell = $this->startWeekday;
        for ($d = 1; $d <= $this->daysInMonth; $d++, $cell++) {
            $today = ($d === (int)date('j') && $this->month === (int)date('n') && $this->year === (int)date('Y'));
            $cls = $today ? ' class="today"' : '';
            echo "<td$cls>$d</td>";

            if ($cell % 7 === 6) {
                echo '</tr><tr>';
            }
        }

        // 尾部填補
        while ($cell % 7 !== 0) {
            echo '<td>&nbsp;</td>';
            $cell++;
        }
        echo '</tr>';
    }

    // 導航連結產生器
    private function prevYear() { return $this->nav($this->year - 1, $this->month); }
    private function prevMonth() {
        $y = $this->month === 1 ? $this->year - 1 : $this->year;
        $m = $this->month === 1 ? 12 : $this->month - 1;
        return $this->nav($y, $m);
    }
    private function nextYear() { return $this->nav($this->year + 1, $this->month); }
    private function nextMonth() {
        $y = $this->month === 12 ? $this->year + 1 : $this->year;
        $m = $this->month === 12 ? 1 : $this->month + 1;
        return $this->nav($y, $m);
    }
    private function nav($y, $m) {
        $y = max(1970, min(2100, $y));
        return "year=$y&month=$m";
    }
}
?>

樣式與調用頁面 (test.php)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP 日曆示範</title>
<style>
.calendar { border-collapse: collapse; margin: 20px auto; font-family: sans-serif; }
.calendar th, .calendar td { width: 40px; height: 35px; text-align: center; border: 1px solid #ddd; }
.calendar th { background: #f0f0f0; font-weight: bold; }
.calendar .today { background: #3498db; color: #fff; font-weight: bold; border-radius: 50%; }
.calendar select { padding: 4px; font-size: 14px; }
.calendar a { text-decoration: none; color: #2c3e50; font-weight: bold; }
.calendar a:hover { color: #3498db; }
</style>
</head>
<body>
<?php
require_once 'calendar.class.php';
$cal = new Calendar();
$cal->render();
?>
</body>
</html>

設計亮點

  • 單一職責:建構子只負責資料初始化,渲染邏輯拆分為多個私有方法
  • 邊界防護:年份限制 1970-2100,月份 1-12,避免 mktime 溢位
  • XSS 防禦:輸出 URL 時使用 htmlspecialchars()
  • 樣式分離:CSS 類名語義化,便於前端客製化
  • 無障礙:使用表單提交而非 JS 跳轉,支援無腳本環境

此實作可直接整合至專案,或作為學習 PHP 日期時間處理、OOP 封裝與模板分離的教學範例。

copyright © 萬盛學電腦網 all rights reserved