Mamamada Mamamada - 13 days ago 7
PHP Question

How to use OOP design patterns to merge two similar functions?

I have two the similar functions, that do verification by generated code. they differ only in body. But logic of them are similar.

public function verifyEmail($code){
// Validaton $code
// Query to DB to get code
// Comparing $code with code from DB
// return success or fail
}

public function verifyPhone($code){
// Validaton $code
// Query to DB to get code
// Comparing $code with code from DB
// return success or fail
}


How can I combine two similar functions, in this case?

Answer

Take these two:

public function verifyEmail($code){
  // Validaton $code
  // Query to DB to get code
  // Comparing $code with code from DB
  // return success or fail
}

public function verifyPhone($code){
  // Validaton $code
  // Query to DB to get code
  // Comparing $code with code from DB
  // return success or fail
}

and make this one:

public function verifyCol($code, $col){

  // white list the column to use in the query to the DB
  // here is an example of a two item white list
  $column = ($col=='Email') ? 'Email' : 'Phone';

  // Validaton $code
  // Query to DB to get code
  // but use the $column variable to select the proper column

  // Comparing $code with code from DB
  // return success or fail
}

also, you can avoid updating legacy code by doing this:

public function verifyEmail($code){
  return verifyCol($code, 'Email');
}
public function verifyPhone($code){
  return verifyCol($code, 'Phone');
}