2014-07-26 66 views
0

我在如何設計我的兩個類時遇到了一些問題,以便避免「複製」和「粘貼」代碼以最大限度地提高可重用性。我有一個創建用戶的課程。本質上,它驗證條目,然後將用戶插入到數據庫中。另一方面,我有另一個類更新用戶,但只有用戶配置文件的一部分。這是我的第一堂課。PHP類繼承和數據驗證

<?php 
class newEmployee extends CoreConnect { 

    protected $_info = array(); 
    protected $_errors = array(); 

    public function __construct($data) { 
     parent::__construct(); 

     $this->_info = array(
      'firstname' => '', 
      'lastname' => '', 
      'street' => '', 
      'postal-code' => '', 
      'province'  => '', 
      'email'   => '', 
      'country'  => '', 
      'userUpdate'  => '', 
      'wage'   => 0, 
      'emp-status' => ''); 

      $this->_info = $data + $this->_info; 
    } 


    protected function validate() { 

     if($this->_info['firstname']=="" || $this->_info['lastname']==""){ 
      $this->_errors[] = "Employee's full name is required"; 
     } 

     if(ctype_alpha ($this->_info['firstname'].$this->_info['lastname'])==false) { 
      $this->_errors[] = "Employee name is invalid"; 
     } 

     if($this->_info['wage']!="") { 
      if(!is_numeric($this->_info['wage'])) { 
       $this->_errors[] = "Salary invalid";  
      } 
     } 

     if($this->_info['userUpdate']=="" && isset($this->_info['userUpdate'])) { 
      $this->_errors[] = "User missing"; 
     }  

     if($this->_info['email']!="") { 
      if (!filter_var($this->_info['email'], FILTER_VALIDATE_EMAIL)) { 
       $this->_errors[] = "Email address is invalid"; 
      } 
     } 



    } 

    public function errors() { 
     return $this->_errors; 
    } 

    public function add(){ 
     $this->validate(); 
     if(empty($this->_errors)) { 
      $params = array(); 
      $query = $this->_INSTANCE->pdo->prepare("INSERT INTO employees 
      (ID, firstname, lastname, email, street, postal_code, province, country, employee_type, member_since) 

      VALUES (NULL, :firstname, :lastname, :email, :street, :postal_code, :province, :country, :status, NOW()) 
         "); 
      $params[":firstname"] = $this->_info["firstname"]; 
      $params[":lastname"] = $this->_info["lastname"]; 
      $params[":street"]  = $this->_info["street"]; 
      $params[":email"]  = $this->_info["email"]; 
      $params[":postal_code"] = $this->_info["postal-code"]; 
      $params[":province"] = $this->_info["province"]; 
      $params[":country"]  = $this->_info["country"]; 
      $params[":status"]  = $this->_info["emp-status"]; 

      return $query->execute($params); 
     } 
    } 
} 

這裏的validate方法驗證我希望驗證哪些條目。該更新用戶的數據的類看起來是這樣的:

<?php 
require_once 'class.newEmployee.php'; 
class updateEmployee extends newEmployee { 

    public function __construct($data) { 
     parent::__construct(); 

     $this->_info = array(
      'employeeID' => "", 
      'firstname' => '', 
      'lastname' => '', 
      'email'  => '', 
      'street' => '', 
      'postal-code' => '', 
      'province'  => '', 
      'country' => ''); 

      $this->_info = $data + $this->_info; 
    } 

    public function update(){ 
     $this->validate(); 


     if(empty($this->_errors)) { 
      $params = array(); 
      $query = $this->_INSTANCE->pdo->prepare("UPDATE employees 
      SET 
       firstname=:firstname, 
       lastname=:lastname, 
       street = :street, 
       postal_code = :postal_code, 
       province = :province, 
       email = :email, 
       country = :country 
      WHERE ID = :ID "); 

      $params[":ID"] = $this->_info["employeeID"]; 
      $params[":firstname"] = $this->_info["firstname"]; 
      $params[":lastname"] = $this->_info["lastname"]; 
      $params[":street"] = $this->_info["street"]; 
      $params[":postal_code"] = $this->_info["postal-code"]; 
      $params[":province"] = $this->_info["province"]; 
       $params[":email"] = $this->_info["email"]; 
      $params[":country"] = $this->_info["country"]; 


      return $query->execute($params); 

     } else { 
      return false; 
     } 
    } 
} 

在這種情況下,我想驗證不僅什麼validate方法從newEmployee驗證也稱爲employeeID新的輸入。基本上我想實現的是能夠以某種方式將父類的部分用於子類,並引入新的驗證。重寫validate方法顯然不方便添加另一個驗證點。進行創建新員工時使用的相同驗證並更新員工是有意義的。在這種情況下,代碼可重用性是必須的,因爲無論是創建員工還是更新他/她的個人資料,它都必須是統一的。

任何建議或引用將是巨大的......

+0

這個問題屬於上[代碼審查(http://codereview.stackexchange.com/)。 –

回答

0

我使用這個類進行驗證,功能「validar」收到兩個參數,firts是數據驗證和第二是規則。

<?php 
/** 
* Esta clase valida todos los datos de entrada al servidor 
*/ 
class Validador 
{ 

    public $errores = array();  


    /** 
    * esta funcion valida las variables que vengan en el post y el get 
    * dependiendo de las reglas recibidas 
    */ 
    public function validar($datos, $reglas){ 

     $valido = TRUE; 

     foreach ($reglas as $campo => $regla) { 

      $verificadores = explode('|', $regla); 

      foreach ($verificadores as $verificador) { 
       $valor = isset($datos[$campo]) ? $datos[$campo] : NULL; 
       if(!$this->$verificador($valor, $campo)){ 
        $valido = FALSE; 
       } 
      } 

     } 
     return $valido; 
    } 

    /** 
    * valida que un valor sea un email valido 
    */ 
    private function email($valor, $campo){ 
     $valido = filter_var($valor, FILTER_VALIDATE_EMAIL); 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." necesita un email valido";    
     } 
     return $valido; 
    } 

    /** 
    * verifica que un valor no este vacio 
    */ 
    private function requerido($valor, $campo){ 
     $valido = !empty($valor); 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." es requerido";    
     } 
     return $valido; 
    } 

    /** 
    * comprueba que un rut sea valido 
    */ 
    private function rut($valor, $campo){ 
     //return TRUE; 
     $dv = substr($valor, -1); 
     $rut = substr($valor, 1,-3); 

     $s=1; 
     for($m=0;$valor!=0;$valor/=10) 
      $s=($s+$valor%10*(9-$m++%6))%11; 

     $valido = chr($s?$s+47:75) == $dv; 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." necesita un rut valido";     
     } 
     return $valido; 
    } 

    /** 
    * verifica que el token recibido sea igual al de la sesion activa 
    */ 
    private function token($valor, $campo){ 
     $valido = $valor == $_SESSION['token']; 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." necesita un token valido";    
     } 
     return $valido; 
    } 

    /** 
    * verifica si el valor recibido es numerico 
    */ 
    private function numero($valor, $campo){ 
     $valido = is_numeric($valor); 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." necesita un numero valido";    
     } 
     return $valido; 
    } 

    /** 
    * verifica si el valor recibido es texto 
    */ 
    private function texto($valor, $campo){ 
     $valido = is_string($valor); 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." necesita un texto valido";    
     } 
     return $valido; 
    } 

    /** 
    * verifica si el valor recibido es un array 
    **/ 
    private function arreglo($valor, $campo){ 
     $valido = is_array($valor); 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." necesita un arreglo valido";     
     } 
     return $valido; 
    } 

    /** 
    * verifica si el valor recibido es un array 
    **/ 
    private function fecha($valor, $campo){ 
     $pattern = '/\d{2}-\d{2}-\d{4}/'; // regex para fecha formato: DD-MM-AAAA ej: 17-07-2014 

     $valido = preg_match($pattern, $valor); 
     if(!$valido){ 
      $this->errores[] = "El campo ".$campo." necesita una fecha valida ej: 14-04-2014";    
     } 
     return $valido; 
    } 
} 

>

,我稱這種方式:

$reglas = array(
       'nombre' => 'requerido', 
       'descripcion' => 'requerido', 
       'token' => 'token|requerido' 
       ); 
$validador = new Validador(); 
if ($validador->validar($_POST, $reglas)) {       
    //valid data       
}else{ 
    // invalid data 
}