2009-10-29 82 views
6

我目前正在開發面向對象的PHP應用程序。我有一個叫做驗證的類,我想用它來檢查提交的所有數據是否有效,但是我顯然需要在某處爲每個要檢查的屬性定義規則。目前,我在構建新對象時使用了數組。例如:PHP對象驗證

$this->name = array(
'maxlength' => 10, 
'minlength' => 2, 
'required' => true, 
'value' => $namefromparameter 
) 

每個屬性的一個數組。

然後,我會調用驗證類中的靜態方法,根據每個數組中定義的值執行各種檢查。

有沒有更有效的方法來做到這一點? 任何意見讚賞。 謝謝。

回答

8

我知道關聯數組通常用於配置PHP的東西(這就是所謂的magic container模式,被認爲是不好的做法,順便說一句),但你爲什麼不創建多個校驗器類來代替,每個能來處理一個規則?事情是這樣的:

interface IValidator { 
    public function validate($value); 
} 

$validators[] = new StringLengthValidator(2, 10); 
$validators[] = new NotNollValidator(); 
$validators[] = new UsernameDoesNotExistValidator(); 

這有多重優勢在使用數組實現:

  • 可以文件他們(非常重要),PHPDoc的無法解析爲數組鍵意見。
  • 你的代碼變得錯字安全(array('reqiured' => true)
  • 它是完全面向對象的,不會引入新的概念
  • 更可讀的(儘管更詳細)
  • 每個約束的實現可以直觀地發現(這不是在400線的功能,但在適當的類別)

編輯:這是一個link to an answer I gavedifferent question,但主要適用於這一個爲好。

+0

好的地方有文檔! – 2009-10-29 08:48:21

+0

謝謝,我以前沒聽說過接口。我會檢查出來的! – Dan 2009-10-29 09:24:59

0

由於使用OO,如果您使用類來驗證屬性,它會更乾淨。例如。

class StringProperty 
{ 
    public $maxLength; 
    public $minlength; 
    public $required; 
    public $value; 
    function __construct($value,$maxLength,$minLength,$required) 
    { 
    $this->value = $value; 
    $this-> maxLength = $maxLength; 
    $this-> minLength = $minLength; 
    $this-> required = $required; 
    } 
    function isValidat() 
    { 
    // Check if it is valid 
    } 
    function getValidationErrorMessage() 
    { 
    } 
} 

$this->name = new StringProperty($namefromparameter,10,2,true); 
if(!$this->name->isValid()) 
{ 
    $validationMessage = $this->name-getValidationErrorMessage(); 
} 

使用類的優點是封裝了數組(基本上是結構)不具有的邏輯。

0

也許受Zend-Framework Validation的啓發。

所以定義主:

class BaseValidator { 
    protected $msgs = array(); 
    protected $params = array();  

    abstract function isValid($value); 
    public function __CONSTRUCT($_params) { 
     $this->params = $_params; 
    } 
    public function getMessages() { 
     // returns errors-messages 
     return $this->msgs; 
    } 
} 

然後生成您的自定義驗證:

class EmailValidator extends BaseValidator { 
    public function isValid($val=null) { 
     // if no value set use the params['value'] 
     if ($val==null) { 
      $val = $this->params['value']; 
     } 
     // validate the value 
     if (strlen($val) < $this->params['maxlength']) { 
      $this->msgs[] = 'Length too short'; 
     } 
     return count($this->msgs) > 0 ? false : true; 
    } 
} 

最後你inital陣列可以成爲這樣的:那麼

$this->name = new EmailValidator(
     array(
      'maxlength' => 10, 
      'minlength' => 2, 
      'required' => true, 
      'value' => $namefromparameter, 
     ), 
    ), 
); 

驗證可能這樣做:

if ($this->name->isValid()) { 
    echo 'everything fine'; 
} else { 
    echo 'Error: '.implode('<br/>', $this->name->getMessages()); 
}