dari88's diary

これから趣味にするプログラミング/PHP/javascript/kohana/CMS/web design/

続 kohanaのテスト12・・・WordPress風画面に動的コンテンツを挿入する

 次はメインのコンテンツ部分に動的なコンテンツを表示してみます。動的コンテンツとしてはテスト9 で作成したページネーション付きの名簿表示画面を流用します。

 

準備

 何でもかんでも controller フォルダに置くのは違和感があります。http:// で直接アクセスさせる必要の無いコントローラは classes フォルダの下にフォルダを作って配置する方針にします。

 テスト9 のコントローラを少し改造します。
・kohana/application/classes/contents/test12.php
 ・フォルダ名の contents とクラス名の Contents を対応させます。
 ・Controlle を継承しません。継承すると kohana の気が狂います。
 ・function に static 属性を持たせています。
 ・最後は画面表示するのではなく、レンダリングして返します。

<?php defined('SYSPATH') OR die('No direct access allowed.');

class Contents_Test12 {

    static function address() {

        $dat = Model::factory('test5');
        $select = $dat->selectData();

        $paginator = Zend_Paginator::factory($select);

        if (isset($_GET['page'])) {
            $page = $_GET['page'];
        } else {
            $page = 1;
        }

        $paginator->setCurrentPageNumber($page);

        $pagecount = $paginator->count();

        $hp = 'test12';
        $firstpage = "$hp?page=1";
        $beforepage = "$hp?page=" . ($page - 1);
        $nextpage = "$hp?page=" . ($page + 1);
        $lastpage = "$hp?page=" . $pagecount;
        if ($page == 1)
            $beforepage = "$hp?page=1";
        if ($page == $pagecount)
            $nextpage = "$hp?page=" . $pagecount;

        // ビュー
        $message = "ページネーションの試験";
        $view = View::factory('test12/main/address');
        $view->message = $message;
        $view->data = $paginator;
        $view->firstpage = $firstpage;
        $view->beforepage = $beforepage;
        $view->nextpage = $nextpage;
        $view->lastpage = $lastpage;

        return $view->render();
    }

}

?>

 

コントローラ

 コントローラは一行変更するだけです。
・kohana/application/classes/controller/test12.php の12行目
 メソッド address に static 属性を持たせたので (::) で呼び出せます。

$view->primary01->article01 = Contents_Test12::address();

 

ビュー

・kohana/application/views/test12/main/address.php
 テスト9 と殆ど同じですが、h1 タグに class 属性を持たせて、WordPress の雰囲気を確保しています。

<h1 class="entry-title"><?php echo $message ?></h1>
<table border="1"><tr>
        <?PHP
        foreach ($data as $d) {
            $id = HTML::chars($d['id']);
            $name = HTML::chars($d['name']);
            $address = HTML::chars($d['address']);
            $tel = HTML::chars($d['tel']);
            print "<tr><td>$id</td> <td>$name</td> <td>$address</td> <td>$tel</td></tr>";
        }
        ?>
    </tr></table>
<?php
echo '<br />';
echo '<a href=' . $firstpage . '>&lt;&lt;</a>';
echo '<a href=' . $beforepage . '>&nbsp;&lt;</a>';
echo '<a> 前のページ     後のページ </a>';
echo '<a href=' . $nextpage . '>&gt;&nbsp;</a>';
echo '<a href=' . $lastpage . '>&gt;&gt;</a>';
?>

 

結果

素晴らしい! 簡単に動的コンテンツを挿入できちゃいました。全体構成はシンプルで、見れば分かるという感じです。こうして眺めていると kohana の設計思想は素晴らしいと思います。これと比べると WordPress のコードなんか、読む気がしません。