このような基本クラスを使用して、コンストラクター段階でそれ自体を自動処理し、指定されたフィールドで特定のフォームを継承できます。いくつかのレンダリング コードも忘れないでください。(これは非常にシステム固有であるため、ここでは表示されません。)
class Form {
protected $name = "generic_form";
protected $method = "POST";
protected $url = "";
protected $fields = array();
protected $data = array();
protected $submits = array();
protected $errors = array();
protected $required = null;
protected $submitsrequired = array();
public function __construct() {
$this->FillSubmits();
$this->FillData();
foreach($this->fields as $key => $value) {
if(isset($this->data[$value["name"]])) {
$this->fields[$key]["value"] = $this->data[$value["name"]];
}
}
$action = null;
foreach($this->submits as $key => $value) {
if (isset($this->data[$value["name"]])) {
$action = $value["name"];
break;
}
}
if ($action === null) {
return;
}
if (!$this->innerValidate($action)) {
return;
}
$this->Commit($action);
}
protected function Validate($action, $name, $value) {
// Put validation code here
}
protected function Commit($action) {
// Put code to execute when form is correctly filled here
}
protected function FillSubmits() {
foreach($this->fields as $field) {
if($field["type"] == "submit")
$this->submits[] = $field;
}
}
protected function FillData() {
foreach($this->fields as $field) {
if(isset($_POST[$field["transmitname"]]))
$this->data[$field["name"]] = $_POST[$field["transmitname"]];
}
}
protected function innerValidate($action) {
$retval = true;
if ($this->required !== null) {
foreach($this->required as $value) {
if (!isset($this->data[$value])) {
return false;
}
}
}
if (isset($this->submitsrequired[$action])) {
foreach($this->submitsrequired[$action] as $value) {
if (!isset($this->data[$value])) {
return false;
}
}
}
foreach($this->data as $key => $value) {
if(is_callable(array($this, "Validate_".$key))) {
$retval &= call_user_func(array($this, "Validate_".$key),$action, $value);
}
else {
$retval &= $this->Validate($action, $key, $value);
}
}
return $retval;
}
}