今回は、メインペジ右側のカレンダー部分を作成する。
ここには、アクセス日の当月のカレンダーを表示し、日記がある日にはその日記へ遷移するリンクを表示する。
<div class="calendar"> カレンダー </div>
を
<div class="calendar"> <?php $this->ShowCalendar(); ?> </div>
とし、ShowCalendarメソッドを実装する。
/// カレンダーを表示する protected function ShowCalendar() { DiaryFuncs::ShowCalendarFunc($this, date('Y'), date('m')); }
DiaryクラスではスタティックなShowCalendarFuncを表示年月を指定して呼び出すだけとする。Diaryクラスで実装することも可能だったが、Diaryクラスがでかくなるのが嫌だったので、別の箇所に実装することとした。
しかし、グローバル関数にするとDiaryのpublicなメソッドしか呼べなくなってしまうので、Diaryクラスを継承したDiaryFuncsというクラスを作成し、そのクラスがDiaryのインスタンスを引数として取るスタティックなメソッドを実装することで解決した。
<?php class DiaryFuncs extends Diary { static function ShowCalendarFunc(Diary $diary, $year, $month) { $lastDay = date('t', strtotime("$year-$month-1")); $diary->ConnectDB(); if($diary->db === FALSE) { $diary->DBErrorDie(); } $sql = "select date, id from diary where date between '{$year}-{$month}-01' and '{$year}-{$month}-{$lastDay}';"; $result = $diary->db->query($sql); if($result === FALSE) { $diary->DBErrorDie(); } $exist = array(); foreach($result as $row) { $day = date('j', strtotime($row['date'])); $exist[$day - 1] = $row['id']; } ?> <table> <tr> <td>日</td><td>月</td><td>火</td><td>水</td><td>木</td><td>金</td><td>土</td> </tr> <?php //一週目を表示 $tmp = getdate(mktime(0, 0, 0, $month, 1, $year)); $wday = $tmp['wday']; echo('<tr>'); for($i = 0;$i < $wday;$i++) { echo('<td></td>'); } for($i = 0;$i < 7 - $wday;$i++) { $isExist = array_key_exists($i, $exist); if($isExist) { echo("<td><a href=\"./?type=DispOne&id={$exist[$i]}\">"); } else { echo('<td>'); } echo($i + 1); if($isExist) { echo('</a>'); } echo('</td>'); } echo("</tr>\n"); //二週目移行の表示 $count = 7 - $wday + 1; while($count <= $lastDay) { echo('<tr>'); for($i = 0;($i < 7) && ($count <= $lastDay);$i++) { $isExist = array_key_exists($count - 1, $exist); if($isExist) { echo("<td><a href=\"./?type=DispOne&id={$exist[$count - 1]}\">"); } else { echo('<td>'); } echo($count); if($isExist) { echo('</a>'); } echo('</td>'); $count++; } echo("</tr>\n"); } ?> </table> <?php } }
シリーズ:
PHPで日記システムを作ってみる1
PHPで日記システムを作ってみる2
PHPで日記システムを作ってみる3
PHPで日記システムを作ってみる4