日記
BMediaNode: PHPプログラマの力量を計る その2 (18:49)Edit

OOPってのは、要はMVCのことなのか。ってことで、MVCで書いてみた。modelをNULLで返すパターンはあんまり美しくないなー。空のmodelでも返した方がきれいか。でもまああまり深く考えることはやめておこう。

index3.php

<?php
main();
function main()
{
header('content-type: text/html; charset=UTF-8');
$ctrl =& new MyController();
$ctrl->run();
$model =& $ctrl->getModel();
$view =& $ctrl->getView();
$view->display($model);
}
class MyController
{
var $_model;
var $_view;
function run()
{
switch ($_SERVER['REQUEST_METHOD']) {
case 'POST':
$this->_model =& new MyModel();
switch ($this->_getMode()) {
case 'input':
$this->_view =& new MyViewInput();
break;
case 'check':
$this->_view =& new MyViewCheck();
break;
case 'result':
$this->_view =& new MyViewResult();
break;
}
break;
default:
$this->_view =& new MyViewInput();
break;
}
}
function _getMode()
{
if (isset($_POST['btnSave']) && $this->_model->isValid()) {
return 'result';
} elseif (isset($_POST['btnNext']) && $this->_model->isValid()) {
return 'check';
} else {
return 'input';
}
}
function &getModel()
{
return $this->_model;
}
function &getView()
{
return $this->_view;
}
}
class MyModel
{
var $_params = array();
var $_errors = array();
function MyModel()
{
$this->_init();
$this->_validate();
}
function _init()
{
$this->_param = array();
$zip = isset($_POST['zip']) ? $_POST['zip'] : '';
$zip = trim(mb_convert_kana($zip, 'KVas'));
$zip = str_replace('-', '', $zip);
$this->_params['zip'] = $zip;
}
function _validate()
{
$this->_errors = array();
if ($this->_params['zip'] == '') {
$this->_errors[] = '入力されていません';
} elseif (!preg_match('|^[0-9]{7}$|', $this->_params['zip'])) {
$this->_errors[] = '入力内容が正しくありません';
}
}
function getParams()
{
return $this->_params;
}
function isValid()
{
return count($this->_errors) == 0;
}
function getErrors()
{
return $this->_errors;
}
}
class MyViewInput
{
function display($model)
{
if (isset($model)) {
extract($model->getParams());
$errors = $model->getErrors();
} else {
$zip = NULL;
}
include 'templates/input.tmpl';
}
}
class MyViewCheck
{
function display($model)
{
extract($model->getParams());
include 'templates/check.tmpl';
}
}
class MyViewResult
{
function display($model)
{
extract($model->getParams());
include 'templates/result.tmpl';
}
}
function h($str)
{
return htmlspecialchars($str);
}
?>

テンプレートは、昨日のやつとはちょっと変わっているんだけど面倒くさいから省略。エラーが配列になって、actionのURLはテンプレート側で解決($_SERVER['PHP_SELF'])するようにしただけ。

より規模が大きいフォームとかに拡張することを考えたプロトタイプとして書くならこういう書き方もありかなー。ただ、これはもともとの仕様を満たすには適材適所を大幅にはみ出ている気がする。

まあ、頭の体操にはいいよね。多分人によっては、MVCの切り分け範囲が違ってくるんだろうな。

ああ

$ctrl->_getMode()が$ctrl->runの中のswitchの条件に依存している。危険危険。

Published At2005-04-20 00:00Updated At2005-04-20 00:00