(Symfony 4) Как получить доступ к пакету Liip Imagine из PHP-кода?

Я хочу иметь возможность загрузить файл, создать из него 3 эскиза и сохранить все на сервере S3.

Мой liip/LiipImagineBundle настроен следующим образом:

liip_imagine :

# configure resolvers
resolvers :

    # setup the default resolver
    default :

        # use the default web path
        web_path : ~

# your filter sets are defined here
filter_sets :

    # use the default cache configuration
    cache : ~

    # the name of the "filter set"
    my_thumb :

        # adjust the image quality to 75%
        quality : 75

        # list of transformations to apply (the "filters")
        filters :

            # create a thumbnail: set size to 120x90 and use the "outbound" mode
            # to crop the image when the size ratio of the input differs
            thumbnail  : { size : [120, 90], mode : outbound }

            # create a 2px black border: center the thumbnail on a black background
            # 4px larger to create a 2px border around the final image
            background : { size : [124, 94], position : center, color : '#000000' }

    # the name of the "filter set"
    thumb_square :

        # adjust the image quality to 75%
        quality : 75

        # list of transformations to apply (the "filters")
        filters :

            thumbnail :  { size : [300, 300], mode : outbound }

            # create a 2px black border: center the thumbnail on a black background
            # 4px larger to create a 2px border around the final image
            background : { size : [304, 304], position : center, color : '#000000' }

    # the name of the "filter set"
    thumb_rectangle_md :

        # adjust the image quality to 75%
        quality : 75

        # list of transformations to apply (the "filters")
        filters :

            thumbnail :  { size : [670, 400], mode : outbound }

            # create a 2px black border: center the thumbnail on a black background
            # 4px larger to create a 2px border around the final image
            background : { size : [674, 404], position : center, color : '#000000' }

    # the name of the "filter set"
    thumb_hd :

        # adjust the image quality to 75%
        quality : 75

        # list of transformations to apply (the "filters")
        filters :

            thumbnail :  { size : [1920, 1080], mode : outbound }

            # create a 2px black border: center the thumbnail on a black background
            # 4px larger to create a 2px border around the final image
            background : { size : [1924, 1084], position : center, color : '#000000' }

Это документация, на которую я смотрю: https://symfony.com/doc/2.0/bundles/LiipImagineBundle/basic-usage.html#runtime-options

Проблема, с которой я сталкиваюсь, заключается в том, что в документации просто сказано сделать это следующим образом:

$this['imagine']->filter('/relative/path/to/image.jpg', 'my_thumb')

Очевидная ошибка, которую я получаю:

Cannot use object of type App\Controller\CreatorDashboard\PostsController as array

Я понимаю, почему я получаю сообщение об ошибке, оно думает, что я пытаюсь использовать свой класс контроллера как массив.

Но как тогда получить доступ к этому Liip/LiipImagineBundle в коде? Как мне получить «дескриптор» в Symfony 4?

Документация не ясна.

Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Symfony Station Communiqué - 17 февраля 2023 г
Symfony Station Communiqué - 17 февраля 2023 г
Это коммюнике первоначально появилось на Symfony Station , вашем источнике передовых новостей Symfony, PHP и кибербезопасности.
Управление ответами api для исключений на Symfony с помощью KernelEvents
Управление ответами api для исключений на Symfony с помощью KernelEvents
Много раз при создании api нам нужно возвращать клиентам разные ответы в зависимости от возникшего исключения.
2
0
2 257
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

Использование $this['imagine'] возможно только при использовании его в PHP-шаблоне. Для использования его в контроллере или службе вы должны получить использовать его как услугу, либо получив его из контейнера (старый стиль использования службы), внедрив его вручную в класс (в файле service.yaml с @liip_imagine.service.filter), либо используя имя класса как службы, которое он предоставляет, точно так же, как вы вводите что-либо из объекта Request, LoggerInterface или большинства других вещей в Symfony 3.3+ (от кода, который появляется до класса Liip\ImagineBundle\Service\FilterService). ).

Ответ принят как подходящий

Пример, которым вы поделились, предназначен для использования шаблона без ветки. Если вы находитесь в контроллере (предположение, основанное на ошибке, которой вы поделились), вам необходимо отключить Liip Cache Manager от контейнера.

/** @var CacheManager */
$imagineCacheManager = $this->get('liip_imagine.cache.manager'); // gets the service from the container

/** @var string */
$resolvedPath = $imagineCacheManager->getBrowserPath('/relative/path/to/image.jpg', 'my_thumb'); // resolves the stored path

Спасибо, харстайлер, это сработало. Мне было интересно, как заставить это работать в классе обслуживания? Потому что я хочу следовать лучшим практикам и сделать контроллер максимально легким.

Brent Heigold 06.02.2019 03:08
symfony.com/doc/current/… Вы должны передать его как аргумент с идентификатором liip_imagine.cache.manager
Fabian Schmick 06.02.2019 08:12

(проверено в Symfony 5) если вы хотите использовать его в сервисе, например (или в контроллере), вы можете ввести Liip\ImagineBundle\Imagine\Cache\CacheManager и используйте его в своем классе:

public function __construct(UploaderHelper $uploaderHelper, CacheManager $cacheManager)
{
    $this->uploaderHelper = $uploaderHelper;
    $this->cacheManager = $cacheManager;
}   
public function getImageLink($image)
{
    $imagePath = $this->uploaderHelper->asset($image, 'imageFile');
    $imageLink = $this->cacheManager->getBrowserPath($imagePath, $imagine_filter);
    return $imageLink;
} 

Другие вопросы по теме