2017-03-02 125 views
3

因爲我不熟悉PHP,我想知道如何減少代碼重複?這兩種方法在這裏做着完全相同的事情......除了提取字符串的部分(filemtimebasename)並加入。如何減少代碼重複

private function modified_hash($files) { 
    $joined = ""; 

    foreach ($files as $file) { 
     $joined .= filemtime($file); 
    } 

    return $this->checksum($joined); 
} 

private function filename_hash($files) { 
    $joined = ""; 

    foreach ($files as $file) { 
     $joined .= basename($file); 
    } 

    return $this->checksum($joined); 
} 

回答

4

相反的兩種功能,聲明一個統一的功能與一個至關重要的回調/函數名$func_name參數:

/** 
* Gets joined files hash 
* 
* @param $files an array of file paths 
* @param $func_name callback name 
* @return mixed 
*/ 
private function getFilesHash($files, callable $func_name) { 
    $joined = ""; 

    foreach ($files as $file) { 
     $joined .= call_user_func($func_name, $file); 
    } 

    return $this->checksum($joined); 
} 

用法:

$fileHash = getFilesHash($files, 'basename'); 

使用的功能: call_user_func

0

我想我的版本是這樣更大然後入鄉隨俗,但作爲一個面向對象的問題,我認爲這是一個可行的解決方案過於:

<?php 

interface HashInterface 
{ 
    public function hash(); 
} 

class ModifiedHash implements HashInterface 
{ 
    public function hash($file) 
    { 
     return filemtime($file); 
    } 
} 

class FileNameHash implements HashInterface 
{ 
    public function hash($file) 
    { 
     return basename($file); 
    } 
} 

class SomeClient 
{ 
    private $hashType; 

    public function setHashType(HashInterface $hashType) 
    { 
     $this->hashType = $hashType; 
    } 

    private function doHash($files) { 
     $joined = ""; 

     foreach ($files as $file) { 
      $joined .= $this->hashType->hash($file); 
     } 

     return $this->checksum($joined); 
    } 
} 

$client = new SomeClient(); 
$files = ???; 

// Want a ModifiedHash? 
$client->setHashType(new ModifiedHash()); 
$data = $client->doHash($files); 

// Want a FileNameHash? 
$client->setHashType(new FileNameHash()); 
$data = $client->doHash($files); 

很抱歉的迷惑類或方法的名稱。我希望你明白了。