0

I'm trying to set my first steps into the OO PHP world. What I'm trying to do is make a class that validates my form input. I know what input fields I need in my entire website and want to make a switch, to do the right thing based on the input field. Lets say we have the input field named 'email', and we have a form for that etc...

First, what I want to do is try to read the $_post names with array_key() function, based on that I have a switch.

Here is my code:

public function __construct ( $var ) {
     $this->arraykeys = array_keys($var);
     $this->error = false;
     $this->message = array();   
}        

public function check() {   

      foreach ($this->arraykeys as $i => $value)
      {

      switch ($value)
      {
        case 'email' :

        $checkmail = new checkEmail($_POST);
        $checkmail->chkEmail($_POST['email']);
        if ($checkmail->chkEmail($_POST['email']) == false)
        {
            array_push($this->message, 'Cannot validate emailadres');
        }            
        break; 

      }


      }

     // print_r($this->field);
}

The check works, but somehow the message array stays empty after an error! I tried everything, but I just can't get it on to the screen!

Please help!

Thanks!!

4

2 回答 2

1

在使用 OOP 之前,您实际上需要一些更基本的对象,使您能够让您的表单处理生效,例如 PHP 超全局变量中的表单字段的面向对象验证以及错误消息:

只是示例:

// defining the interfaces and classes of the form values and validation, form field 
// and fields
Interface FormValue
{
    public function getValue();
}

interface FormValueValidator
{
    /**
     * @param FormValue $value
     * @return bool
     */
    public function validate(FormValue $value);
}

class NamedFormValue implements FormValue
{
    private $name;
    private $value;

    public function __construct(array $data, $name, $default = null)
    {
        $this->name = $name;
        $this->value = isset($data[$name]) ? $data[$name] : $default;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function getName()
    {
        return $this->name;
    }
}

class EmailValidator implements FormValueValidator
{
    public function validate(FormValue $value)
    {
        $result = filter_var((string) $value->getValue(), FILTER_VALIDATE_EMAIL);
        return is_string($result);
    }
}

class FormFieldFactory
{
    /**
     * @param $name
     * @param array $field
     * @return FormField
     */
    public function create($name, array $field)
    {
        $validatorClass = sprintf('%sValidator', @$field['validator']);
        $validator = new $validatorClass;

        $formField = new FormField($name);
        $formField->setValidator($validator);
        $formField->setErrorMessage($field['error_msg']);
        return $formField;
    }
}

class FormField
{
    private $name;
    /**
     * @var FormValueValidator
     */
    private $validator;
    private $errorMessage;
    /**
     * @var FormValue
     */
    private $value;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function setValidator(FormValueValidator $validator)
    {
        $this->validator = $validator;
    }

    public function isValid()
    {
        return $this->validator->validate($this->value);
    }

    public function setErrorMessage($errorMessage)
    {
        $this->errorMessage = $errorMessage;
    }


    public function getErrorMessage() {
        return $this->errorMessage;
    }

    public function setValue(FormValue $value)
    {
        $this->value = $value;
    }

    /**
     * @return FormValue
     */
    public function getValue()
    {
        return $this->value;
    }
}

class FormFields extends IteratorIterator
{
    private $fieldFactory;
    private $invalidFields;

    public function __construct(array $definitions, $fieldFactory)
    {
        parent::__construct(new ArrayIterator($definitions));
        $this->fieldFactory = $fieldFactory;
    }

    public function current()
    {
        $name = $this->getInnerIterator()->key();
        $definition = $this->getInnerIterator()->current();
        return $this->fieldFactory->create($name, $definition);
    }

    public function valid()
    {
        return $this->getInnerIterator()->valid();
    }

    /**
     * @param array $data
     * @return bool true on success, false on validation error
     */
    public function validateOn(array $data)
    {
        $this->invalidFields = array();

        foreach($this as $name => $field) {
            /* @var $field FormField */
            $value = new NamedFormValue($data, $name);
            $field->setValue($value);
            $valid = $field->isValid();
            $valid || ($this->invalidFields[$name] = $field);
        }

        return 0 === count($this->invalidFields);
    }

    /**
     * @return FormField[]
     */
    public function getInvalidFields()
    {
        return $this->invalidFields;
    }
}

// defining the form in array notation:
$form = array(
    'fields' => array(
        'email' => array(
            'validator' => 'Email',
            'error_msg' => 'Cannot validate emailadress',
        ),
    ),
);

// processing the form validation
$messages = array();
$fields = new FormFields($form['fields'], new FormFieldFactory());
$fields->validateOn($_POST)
foreach ($fields->getInvalidFields() as $field) {
    $messages[] = $field->getErrorMessage();
}
var_dump($messages);

示例输出:

array(1) {
  [0]=>
  string(27) "Cannot validate emailadress"
}
于 2012-07-24T17:30:44.597 回答
0

试试这个:

public function check()
{   

      foreach ($this->arraykeys as $i => $value)
      {

      switch ($value)
      {
        case 'email' :

        $checkmail = new checkEmail($_POST);
        $checkmail->chkEmail($_POST['email']);
        if ($checkmail->chkEmail($_POST['email']) == false)
        {
            $this->message[] = 'Cannot validate emailadres';
        }            
        break; 

      }


      }

     print_r($this->message);
}

还要确保您的属性设置为公开。

你确定$checkmail->chkEmail()是假的并且运作良好吗?

于 2012-07-24T16:05:10.127 回答