你也可以创建一个测试用例以验证form表单何时有效:
class FormHandlerTestCase extends UnitTestCase { // ... function testValidate() { $post =& new Post; $post->set(‘fname’, ‘Jason’); $post->set(‘lname’, ‘Sweat’); $post->set(‘email’, ‘jsweat_php@yahoo.com’); $form = FormHandler::build($post); $this->assertTrue(FormHandler::validate($form, $post)); $this->assertNoUnwantedPattern(‘/invalid/i’, $form[0]->paint()); $this->assertNoUnwantedPattern(‘/invalid/i’, $form[1]->paint()); $this->assertNoUnwantedPattern(‘/invalid/i’, $form[2]->paint()); } }
这又提出了在本方法内追踪任何验证失败的需求,因此它可以返回true如果所有的都合格。
class FormHandler { // ... function validate(&$form, &$post) { $valid = true; // first name required if (!strlen($post->get(‘fname’))) { $form[0] =& new Invalid($form[0]); $valid = false; } // last name required if (!strlen($post->get(‘lname’))) { $form[1] =& new Invalid($form[1]); $valid = false; } 214 The Decorator Pattern // email has to look real if (!preg_match(‘~\w+@(\w+\.)+\w+~’ ,$post->get(‘email’))) { $form[2] =& new Invalid($form[2]); $valid = false; } return $valid; } }
那些就是所有需要为页面添加验证的building blocks 。这里是本游戏(章)结尾的一个截图。

以及产生它的页面代码:
<html> <head> <title>Decorator Example</title> <style type=”text/css”> .invalid {color: red; } .invalid input { background-color: red; color: yellow; } #myform input { position: absolute; left: 110px; width: 250px; font-weight: bold;} </style> </head> <body> <form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”> <div id=”myform”> <?php error_reporting(E_ALL); require_once ‘widgets.inc.php’; $post =& Post::autoFill(); $form = FormHandler::build($post); if ($_POST) { FormHandler::validate($form, $post); } foreach($form as $widget) { echo $widget->paint(), “<br>\n”; The Decorator Pattern 215 } ?> </div> <input type=”submit” value=”Submit”> </form> </body> </html>
总结
装饰器模式是对你产生影响的那些模式中的另一个,当你使用他们工作一段时间以后。装饰器模式允许你可以简单的通过严格的继承问题。你可以这样认为装饰器:在运行时可以有效地改变对象的类或者甚至多次—当你在你的脚本不同的场合使用这个类。
也许装饰器模式最重要的一个方面是它的超过继承的能力。“问题”部分展现了一个使用继承的子类爆炸。基于装饰器模式的解决方案,UML类图展现了这个简洁灵活的解决方案。

下文:《PHP设计模式介绍》第十三章 适配器模式
本文链接:http://www.blueidea.com/tech/program/2008/6091.asp
出处:phpchina
责任编辑:bluehearts
上一页 php设计模式介绍之装饰器模式 [5] 下一页
◎进入论坛网络编程版块参加讨论
|