繁体   English   中英

我该如何改进这个PHP代码?

[英]How can I improve this PHP code?

我有下面的PHP代码,帮助我在脚本中获取照片的缩略图图像路径

这将从mysql DB'2 / 34/12 / thepicture.jpg中获取这样的提供值。然后将它转换为'2/34/12 / thepicture_thumb1.jpg'

我相信有更好的表现方式,我愿意接受任何帮助

此外,在一个有50个用户的页面上,这将运行50次以获得50张不同的照片

// the photo has it is pulled from the DB, it has the folders and filename as 1
$photo_url = '2/34/12/thepicture_thumb1.jpg';
//build the full photo filepath
$file = $site_path. 'images/userphoto/' . $photo_url;
// make sure file name is not empty and the file exist 
if ($photo_url != '' && file_exists($file)) {
    //get file info
    $fil_ext1 = pathinfo($file);
    $fil_ext = $fil_ext1['extension'];
    $fil_explode = '.' . $fil_ext;
    $arr = explode($fil_explode, $photo_url);
    // add "_thumb" or else "_thumb1" inbetween 
    // the file name and the file extension 2/45/12/photo.jpg becomes 2/45/12/photo_thumb1.jpg
    $pic1 = $arr[0] . "_thumb" . $fil_explode;
    //make sure the thumbnail image exist
    if (file_exists("images/userphoto/" . $pic1)) {
        //retunr the thumbnail image url
        $img_name = $pic1;
    }
}

我很好奇的一件事是它如何使用pathinfo()来获取文件扩展名,因为扩展名总是3位数,是否有其他方法可以获得更好的性能?

这段代码是否存在性能问题,或者您只是过早优化? 除非性能严重到足以成为可用性问题,并且分析器告诉您这个代码应该受到责备,否则此代码存在更多紧迫问题。

回答这个问题:“我该如何改进这个PHP代码?” 添加空格。

性能方面,如果您调用内置PHP函数,性能非常好,因为您在后台运行已编译的代码。

当然,在你不需要的时候调用所有这些函数并不是一个好主意。 在您的情况下, pathinfo函数返回您需要的各种路径。 当您可以像这样构建文件名时,可以在原始名称上调用explode函数(注意,'filename'仅在PHP 5.2之后可用):

$fInfo = pathinfo($file);
$thumb_name = $fInfo['dirname'] . '/' . $fInfo['filename'] . '_thumb' . $fInfo['extension'];

如果您没有PHP 5.2,那么最简单的方法是忽略该函数并使用strrpossubstr

// gets the position of the last dot
$lastDot = strrpos($file, '.');
// first bit gets everything before the dot,
// second gets everything from the dot onwards
$thumbName = substr($file, 0, $lastDot) . '_thumb1' . substr($file, $lastDot);

此代码的最佳优化是提高它的可读性:

// make sure file name is not empty and the file exist 
if ( $photo_url != '' && file_exists($file) ) {

    // Get information about the file path
    $path_info = pathinfo($file);

    // determine the thumbnail name 
    // add "_thumb" or else "_thumb1" inbetween 
    // the file name and the file extension 2/45/12/photo.jpg
    // becomes 2/45/12/photo_thumb.jpg
    $pic1 = "{$path_info['dirname']}/{$path_info['basename']}_thumb.{$fil_ext}";

    // if this calculated thumbnail file exists, use it in place of
    // the image name
    if ( file_exists( "images/userphoto/" . $pic1 ) ) {
        $img_name = $pic1;
    }
}

我使用换行符分解了函数的组件,并使用pathinfo()返回的信息来简化确定缩略图名称的过程。

更新以包含来自@DisgruntledGoat的反馈

你为什么甚至关心这个功能的表现? 假设您只调用一次(例如,生成“main”文件名时)并存储结果,则与DB和文件系统访问相比,其运行时应基本为零。 如果你在每次访问时调用它来重新计算缩略图路径,那么这很浪费,但它仍然不会对运行时产生重大影响。

现在,如果您希望它看起来更好并且更易于维护,那么这是一个有价值的目标。

解决这个问题的最简单方法是手动缩放所有用户个人资料照片,并保留它,这样你就不会继续调整大小。

$img_name = preg_replace ('/^(.*)(\\..*?)$/', '\\1_thumb\\2', $file);

编辑:bbcode用\\消失了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM