如何减少代码重复

时间:2017-03-02 21:17:08

标签: php optimization

由于我不熟悉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 );
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我想我的版本比Romans大一些,但作为一个OOP问题,我认为这也是一个可能的解决方案:

<?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);

对于令人困惑的类或方法名称感到抱歉。我希望你有这个想法。