最小限のMVCのサンプル
Java/Servletではforwardというのがあるが、PHPではforwardはできないので、controller.phpがview.phpをインクルードすることによってビューにデータを渡す。
---------------------------------------------------------------------------------------------------------------------------------------------------------controller.php
<?php // コントローラ // ユーザが最初にアクセスするphp。 // index.phpという名前にしてもよい。 require_once("model.php"); session_start(); function redirect($pagename) { if (headers_sent()) { exit("Error: redirect: Already header has sent!"); } $host = $_SERVER['HTTP_HOST']; $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); header("Location: http://$host$uri/$pagename"); exit; } // action は必ず GET で渡す。 // POST を一切使いたくない画面もあるから。 if (array_key_exists("action", $_GET)) $action = $_GET["action"]; else $action = ""; switch ($action) { case "": require_once("view.php"); // 初期表示表示 break; case "dbaccess": $result = dbaccess(); $nextpage = $result[0]; $_SESSION["data"] = $result[1]; // ビューに渡すデータ switch ($nextpage) { case "success": redirect("success.php"); // 成功画面表示 break; case "failure": redirect("failure.php"); // 失敗画面表示 break; } break; default: echo "action の値が変です: [{$action}]"; break; } ?>---------------------------------------------------------------------------------------------------------------------------------------------------------
model.php
<?php function dbaccess() { // コントローラに返すデータを初期化 $result = array("", array()); // パラメータの取得はコントローラでなくモデルの中でやった方がいいと思う。 $t1 = $_POST["t1"]; if ($t1 == "hoge") { $result[0] = "success"; } else { $result[1]["msg"] = "よくわからないエラー"; // ビューに渡すデータ $result[0] = "failure"; } return $result; } ?>---------------------------------------------------------------------------------------------------------------------------------------------------------
view.php
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <h1>view.php</h1> 下のテキストボックスに「hoge」と入力した場合だけ成功します。<br> <form name="f1" action="controller.php?action=dbaccess" method="POST"> <input type="text" id="t1" name="t1" maxlength=10><br> <input type="submit" value="送信"> </form> </body> </html>---------------------------------------------------------------------------------------------------------------------------------------------------------
success.php
成功画面。
実際は成功した場合の遷移先もこんな単純ではないだろうから、MVCにしてsuccess.phpをコントローラにするとよい。
<html> <head> <meta content="text/html"; charset="utf-8"> </head> <body> 成功です! </body> </html>---------------------------------------------------------------------------------------------------------------------------------------------------------
failure.php
失敗画面
<?php if (!isset($msg)) $msg = ""; ?> <html> <body> 失敗です!<br> 原因:<?php echo $msg;?><br> <input type="button" value="戻る" onclick="history.back();"><br> </body> </html>---------------------------------------------------------------------------------------------------------------------------------------------------------
没有评论:
发表评论