Оптимизация функции формирования ссылки на изображение

Автор kdvbpspr, 11 января 2019, 15:19:09

« назад - далее »

kdvbpspr

Сейчас функция отображения картинок делает двойную проверку на наличие файла на диске сервера.
Было бы правильно вынести это в отдельную регламентную задачу, а вывод информации осуществлять на основе предварительной обработки данных.

/classes/Link.php

Здесь прошу обратить внимание на функцию file_exists - она вызывает вызов системных функций и обращение к жесткому диску. Это одна из причин высокой нагрузки на сервер по php-fpm

public function getImageLink($name, $ids, $type = null)
    {
        $not_default = false;

        // Check if module is installed, enabled, customer is logged in and watermark logged option is on
        if (Configuration::get('WATERMARK_LOGGED') && (Module::isInstalled('watermark') && Module::isEnabled('watermark')) && isset(Context::getContext()->customer->id)) {
            $type .= '-'.Configuration::get('WATERMARK_HASH');
        }

        // legacy mode or default image
        $theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
        if ((Configuration::get('PS_LEGACY_IMAGES')
            && (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
            || ($not_default = strpos($ids, 'default') !== false)) {
            if ($this->allow == 1 && !$not_default) {
                $uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
            } else {
                $uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
            }
        } else {
            // if ids if of the form id_product-id_image, we want to extract the id_image part
            $split_ids = explode('-', $ids);
            $id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
            $theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
            if ($this->allow == 1) {
                $uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
            } else {
                $uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
            }
        }

        return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
    }


P.S. 1.6

mistral

ЦитироватьСамый быстрый способ проверить наличие локального файла – stream_resolve_include_path () :
if (false !== stream_resolve_include_path($s3url)) { //do stuff }
Результаты производительности stream_resolve_include_path () vs file_exists () :
Test name Repeats Result Performance
stream_resolve 10000 0.051710 sec +0.00%
file_exists 10000 0.067452 sec -30.44%

Adik


kdvbpspr

#3
Спасибо за ответы!

Есть ли варианты избавиться от двойной проверки на наличие файла на диске сервера?

В функции
public function getImageLink($name, $ids, $type = null)

Adik

Можно закоментировать проверку.
Если сам запоняешь товары и картинки у всех есть, тогда ошибок не будет.