我成为一名 PHP 开发人员已经有一段时间了,但直到今天我还没有找到一种简单的处理方法(也就是规范化、清理、验证、填充和显示表单及其各自的字段错误)。
我知道现在大多数 PHP 框架都使这项工作变得更容易,但不知何故我不想将我的所有代码移植到这些框架之一,而且我不太明白表单验证是如何在 Django 中实现的实例(我知道,它是 Python,但我真的很喜欢他们的方法),所以我认为最好的方法是在这里发布我处理简单表单的方式,也许你们可以指出我最好的方向。
<?php
// sample controller
class _sample extends framework
{
// sample action
function contact()
{
if ($this->Is->Post() === true)
{
$errors = array();
if ($this->Is->Set($_POST['name']) === false)
{
$errors['name'] = 'Please fill in your name.';
}
if (($this->Is->Email($_POST['email']) === false) || ($this->Is->Set($_POST['email']) === false))
{
$errors['email'] = 'Please fill in your email address.';
}
if (($this->Is->Phone($_POST['contact']) === false) && ($this->Is->Mobile($_POST['contact']) === false))
{
$errors['contact'] = 'Please fill in your phone (or cell phone) number.';
}
if ($this->Is->Set($_POST['message']) === false)
{
$errors['message'] = 'Please type a message';
}
// no errors, it's valid!
if (empty($errors) === true)
{
// do stuff and redirect to "success" / "thank you" page
}
// load the form view, and let it display the errors
// automatically prefill fields with $_POST values
else
{
$this->View('contact_form', $errors);
}
}
// load the form view for the first time
else
{
$this->View('contact_form');
}
}
}
?>
如您所见,这应该是一个简单的联系表单,但它让我费尽心思去验证它,我一直在研究一些设计模式(Observer、Factory),但我不确定是否和我应该以什么方式实现它们。
最佳答案
恕我直言,将表单视为单一概念的尝试是失败的。如果您的应用程序有任何类型的分层架构,表单很可能会跨越这些架构。表单有应用逻辑( Controller 层),它们有可视化表示( View 层),它们有状态(应用层模型),最后它们通常调用某种事务脚本(模型层)。
我认为您最好放弃将“表单”作为一个实体的想法,而是将注意力集中在完全独立的三个部分(输入处理、渲染和模型层)上,这可能(或可能不会) ) 恰好彼此密切相关。这有时被称为 MVC 模式,尽管这个术语现在已经被广泛使用以至于它可能意味着很多事情。
关于php - 如何简化 PHP 中的表单处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/740278/