php教程:php设计模式介绍之装饰器模式(4)

http://www.itjxue.com  2015-07-17 08:20  来源:未知  点击次数: 

想更方便的话,你可以使用Factory模式或者自动填充的方法来从$_POST里面提取关键字。

class Post {
// ...
function &autoFill() {
$ret =& new Post;
foreach($_POST as $key => $value) {
$ret->set($key, $value);
}
return $ret;
}
}

使用这个Post类,你可以编辑你的FormHandler::build()  方法,默认使用已经存在的$_post数据:

class FormHandler {
function build(&$post) {
return array(
new Labeled(‘First Name’
, new TextInput(‘fname’, $post->get(‘fname’)))
,new Labeled(‘Last Name’
, new TextInput(‘lname’, $post->get(‘lname’)))
,new Labeled(‘Email’
, new TextInput(‘email’, $post->get(‘email’)))
);
}
}

现在你可以创建一个php脚本使用FormHandler类来产生HTML表单:

<form action=”formpage.php” method=”post”>
<?php
210 The Decorator Pattern
$post =& Post::autoFill();
$form = FormHandler::build($post);
foreach($form as $widget) {
echo $widget->paint(), “<br>\n”;
}
?>
<input type=”submit” value=”Submit”>
</form>

现在,你已经拥有了一个提交给它自身并且能保持posted数据的表单处理(form handler) 类。

现在。我们继续为表单添加一些验证机制。方法是编辑另一个组件装饰器类来表达一个“invalid”状态并扩展FormHandler类增加一个validate()方法以处理组件示例数组。如果组件非法(“invalid”),我们通过一个“invalid”类将它包装在<span>元素中。这里是一个证明这个目标的测试     

class WidgetTestCase extends UnitTestCase {
// ...
function testInvalid() {
$text =& new Invalid(
new TextInput(‘email’));
$output = $text->paint();
$this->assertWantedPattern(
‘~^<span class=”invalid”><input[^>]+></span>$~i’, $output);
}
}

 这里是Invalid  WidgetDecorator子类:
//代码Here’s the Invalid WidgetDecorator subclass:

class Invalid extends WidgetDecorator {
function paint() {
return ‘<span class=”invalid”>’.$this->widget->paint().’</span>’;
}
}

(责任编辑:IT教学网)

更多