如何使用OOP设计模式合并两个相似的函数?

时间:2016-11-23 17:33:48

标签: php oop

我有两个类似的功能,通过生成的代码进行验证。它们只在身体上有所不同。但它们的逻辑是相似的。

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
}

在这种情况下,我如何组合两个相似的功能?

2 个答案:

答案 0 :(得分:0)

我不知道如何使用OOP,我认为使用程序性思维就是你想要的。

private function vertifyThing($type, $code)
{
    // Validaton $code (based off of $type)
    // Query to DB to get code (based off of $type)
    // Comparing $code with code from DB (based off of $type)
    // return success or fail 
}

public function verifyEmail($code)
{
    return vertifyThing('email', $code);
}

public function verifyPhone($code)
{
    return vertifyThing('phone', $code);
}

答案 1 :(得分:0)

拿这两个:

@item

并制作这个:

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
}

此外,您可以通过执行以下操作来避免更新旧代码:

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
}