Как предотвратить создание дубликатов файлов OctoberCMS

#php #twig #octobercms #octobercms-plugins

Вопрос:

У меня есть часть, которая создает отзывчивое изображение для моего сайта. Это и есть код:

 [viewBag]
==
<?php
function onStart()
{
    // $this['src'] is a file object
    // e.g. for uploaded files in public directory
    if ($this['src'] instanceof SystemModelsFile) {
        $this['width'] = $this['src']->getWidthAttribute();
        $this['public_path'] = $this['src']->path;
    }
    // $this['src'] is a string
    else {
        $this['public_path'] = SystemClassesMediaLibrary::url($this['src']);

        // Relative path provided
        if (!file_exists($this['src'])) {
            $this['local_path'] = base_path() . Config::get('cms.storage.media.path') . '/' . $this['src'];
        }
        // Full path provided
        else {
            $this['local_path'] = $this['src'];
        }

        // Get width of original image
        $file = new OctoberRainDatabaseAttachFile;
        $file->fromFile($this['local_path']);
        $this['width'] = $file->getWidthAttribute();
        $this['image_from'] = 'media';
    }

    if (isset($this['max_width']) amp;amp; $this['max_width'] < $this['width']) {
        $this['width'] = $this['max_width'];
    }
}
?>
==
<img
  class="{{ class }}"
  src="{% if width <= 1600 %}{{src}}{% else %}{{ public_path|resize(1600,1600) }}{% endif %}"
  srcset="
    {% if width >= 500 %}{{ public_path|resize(500,500) }} 500w {% endif %}
    {% if width >= 768 %},{{ public_path|resize(768,768) }} 768w {% endif %}
    {% if width >= 1200 %}, {{ public_path|resize(1200,1200) }} 1200w {% endif %}
    {% if width >= 1600 %}, {{ public_path|resize(1600,1600) }} 1600w {% endif %}
    {% if width >= 2000 %}, {{ public_path|resize(2000,2000) }} 2000w {% endif %}
    {% if width >= 2500 %}, {{ public_path|resize(2500,2500) }} 2500w {% endif %}
    {% if width >= 3000 %}, {{ public_path }} 3000w {% endif %}"
  sizes="
    {% if width >= 500 %}(max-width: 500px) 500px{% endif %}
    {% if width >= 768 %},(max-width: 768px) 768px{% endif %}
    {% if width >= 1200 %}, (max-width: 1200px) 1200px{% endif %}
    {% if width >= 1600 %}, (max-width: 1600px) 1600px{% endif %}
    {% if width >= 2000 %}, (max-width: 2000px) 2000px{% endif %}
    {% if width >= 2500 %}, (max-width: 2500px) 2500px{% endif %}
    {% if width >= 3000 %}, 3000px{% endif %}"
  alt="{{ alt }}"
>
 

Затем я использую это в своей веточке вот так:

 {% partial 'responsive-image' src='hotel/pool.jpg' class='jarallax-img' alt='background image' %}
 

Это успешно создает уменьшенные изображения, однако, проверяя в моем storage/app/uploads/public каталоге, кажется, что он дублирует полноразмерные изображения при каждом отдельном запросе, а затем сохраняет их в случайных подкаталогах там. К сожалению, это быстро расходует доступное пространство на жестком диске.

Ответ №1:

Часть, которая дублирует изображение, это:

 // Get width of original image
$file = new OctoberRainDatabaseAttachFile;
$file->fromFile($this['local_path']);
$this['width'] = $file->getWidthAttribute();
 

Вот почему он создает новую копию исходного изображения по каждому запросу.

К счастью, в PHP есть встроенная функция для получения ширины изображения, поэтому вам даже не нужно использовать OctoberCMS для получения ширины:

 $this['width'] = getimagesize($this['local_path'])[0];