Skip to main content.

Thursday, November 23, 2006

Guesswork classic(その2)

PHPのフレームワークであるguesswork classicをまた使ってみました。前回、このguesswork classicの記事を書いてからもう1年以上経過しましたが、特に実務で利用する機会もなかったです。(といいますか、開発実務ではこの1年のWeb系はJavaベースばかりでした。)それで、guessworkのページを見ると特に更新されている様子はないですが、guesswork classicをもう少し試してみました。

試したポイントは、コントロールとアクションメソッドの名前の関係です。guesswork classicの特徴として、コントロールとアクションの関係は設定ファイルに記述するのではなく、名前で関係付けられます。前回の記事にも書きましたが、例えば、コントロールクラスのスクリプトファイルを"application.php"とすると、"application.php?action=input"でinputアクションメソッドが呼ばれ、"application.php?action=result"でresultアクションメソッドが呼ばれます。このactionパラメータでメソッドを切り替えます。

今回はこのあたりを確認するために、ユーザ管理のようなシステムを意識してコントローラを中心に作成しました。(※実際の実行はこちらから実行出来ます。)実際にはほとんど処理をしていませんし、セッション管理も出来ていないですが、以下のアクションがあります。

・initLoginアクション(デフォルトアクション)
・loginアクション
・listアクション
・searchInputアクション

処理の流れとしては、initLoginアクションからloginアクションを呼び出して、loginアクションでログインした後にメニューが表示され処理が分岐するという流れです。

実装の特徴としては、コントローラに直接処理を記述していることでしょうか。実際には小規模のシステムですと一つのコントローラにそのまま処理自体を記述していっても何とかなるでしょうが、規模が大きくなると単純に記述していくと同じような処理を書くことが増えたり、プログラムが大きくなり過ぎて分かりにくいということになります。当然ですが、そのあたりは事前の設計が必要となります。実際には処理自体は別のクラスを作成して、コントローラからはそのクラスへデータを渡して処理自体はクラスで行うことになるかと思います。また、コントローラを複数に分割するということもあるかと思います。

あと、listアクションで、MySQLの関数を使用してデータを取得していますが、これではMVCのModelとは言いがたい実装なので、MVCというなら、Modelを意識したクラス設計、実装が必要となります。そのあたりは、例えばですが、最後の参考サイトを参考にして下さい。

ソースファイル、テンプレートファイル(※スタイルシートのないHTMLファイルですが)は以下になります。guesswork classicディレクトリ構成は決まっていませんので、コントローラにパスを記述しています。あと、テンプレートエンジンとして、smartyが必要です。

コントローラのソースファイル
<?php
require_once "../../libs/Guesswork.php";
require_once "./UserValidator.class.php";

/**
 * サンプル用、テスト用ユーザ管理システムコントローラ
 */
class UserController extends Controller
{
    // デフォルトアクションの設定
    var $_gw_default_action = "initLogin";

    // Smartyのディレクトリの設定
    var $_gw_template_class = "../../libs/Smarty.class.php";
    var $_gw_template_templates_dir = '../../smarty/templates';
    var $_gw_template_compile_dir = '../../smarty/templates_c';

    // コントローラのパス(HTMLフォーム埋め込み用)
    var $controllerPath;

    // エラーメッセージ配列
    var $errors;

    // フォーム項目
    var $userid;
    var $passwd;
    var $datas;

    // 初期化
    function init()
    {
        $this->controllerPath = $_SERVER['PHP_SELF'];
        $this->errors = array();
        $this->userid = "";
        $this->passwd = "";
    }   

    //------------------------------------
    // 初回ログイン(initLoginアクション)
    // 初回ログイン処理
    // フォーム表示前処理
    function prepareInitLogin()
    {

    }

    function executeInitLogin()
    {
        return $this->render('user/login');
    }
    //------------------------------------


    //------------------------------------
    // ログイン(loginアクション)
    // フォーム表示前処理
    function prepareLogin()
    {

    }

    // ログイン処理
    function executeLogin()
    {
        // エラーがあった場合はログインフォームを表示
        if (!$this->validate()) {
            $this->errors = $this->getErrors();
            return $this->render('user/login');

        }else{
        // 何か入力すればメニューを表示するだけで、特に処理はしていない。
            return $this->render('user/menu');
        }
    }
    //------------------------------------


    //------------------------------------
    // ユーザ一覧(listアクション)
    function prepareList()
    {

    }
    // ユーザ一覧 
    function executeList()
    {
        // MySQLからのデータ取得
        $con = mysql_connect("myserver", "myuser", "mypassword");
             or die("Could not connect");

        mysql_select_db("weblog")
             or die("Could not select database");

        $query = "select * from tTestCustomer";

        $result = mysql_query($query)
             or die("検索できませんでした。");

        while($array = mysql_fetch_row($result)){
             $this->datas[] = array('id'=>$array[0],
             'name'=>$array[1],
             'prefectures'=>$array[2],
             'email'=>$array[3]);
        }
        mysql_close($con);

        return $this->render('user/list');
    }
    //------------------------------------


    //------------------------------------
    // 検索条件入力(searchInputアクション)
    // 検索条件入力処理
    // フォーム表示前処理
    function prepareSearchInput()
    {

    }

    function executeSearchInput()
    {
        return $this->render('user/searchInput');
    }
    //------------------------------------
}

$controller = new UserController();
$controller->process();

exit;
?>

Validatorクラスのソースファイル
<?php
/**
 * サンプル、テスト用ユーザ管理システムValidator
 */
class UserValidator extends Validator
{
    // Loginアクションでの検証
    function validateLogin($values)
    {
        if ($this->isEmpty($values["userid"])) {
            $this->addError("userid", "ユーザIDが入力されていません。");
        }

        if ($this->isEmpty($values["passwd"])) {
            $this->addError("passwd", "パスワードが入力されていません。");
        }
    }


    // SearchInputアクションでの検証
    function validateSearchInput($values)
    {

    }
}
?>

loginのテンプレートファイル
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
        <title>ログイン</title>
        <meta http-equiv="Content-Type" content="text/html; charset=EUC-JP" />
</head>

<body>

<h3>ユーザ管理・ログイン</h3><hr>

<form method="post" action="{$controllerPath}">
<input type="hidden" name="action" value="login" />

<p>
ユーザID:
<br>
<input size="20" maxlength="10" name="userid" value="" type="text">

</p><p>
パスワード:
<br>
<input size="20" maxlength="10" name="passwd" value="" type="password">

</p><p>
<input value="ログイン" type="submit">

</p></form>

<p>
{if $errors.userid}{$errors.userid}<br>{/if}
{if $errors.passwd}{$errors.passwd}<br>{/if}
</p>

<p>
ユーザ名、パスワードに何か入力すればいいです
</p>

</body>

</html>

menuのテンプレートファイル
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
        <title>メニュー</title>
        <meta http-equiv="Content-Type" content="text/html; charset=EUC-JP" />
</head>

<body>

<h3>ユーザ管理・メニュー</h3><hr>

<a href="{$controllerPath}?action=list">ユーザ一覧<br></a>
<a href="{$controllerPath}?action=searchInput">ユーザ検索<br></a>


</body>

</html>

listのテンプレートファイル
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-JIS">
</head>

<h3>ユーザ管理・一覧</h3>
<hr>

検索結果<br>
(※架空の情報です。)<br>

<table border="1">
<tr>
        <th>ID</th>
        <th>NAME</th>
        <th>PREFECTURES</th>
        <th>MAIL</th>
</tr>
{foreach from=$datas item="item"}
<tr>
        <td>{$item.id}</td>
        <td>{$item.name}</td>
        <td>{$item.prefectures}</td>
        <td>{$item.email}</td>
</tr>
{/foreach}
</table>

</html>

searchInputのテンプレートファイル
<html>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-JIS">

<h3>ユーザ管理・検索条件入力</h3>
<hr>

検索条件入力、検索実行ボタンのフォームを作成します


</html>


掲載したプログラムはサンプル程度です。このプログラムを利用しての不具合、不利益には一切の責任を負いかねます。ご了承ください。

関連リンク
guesswork
guesswork classic
参考サイト
スタックアスタリスク PHPでMVC 第1回:前編
スタックアスタリスク PHPでMVC 第2回:後編

Webプログラミング関連記事