cancel
Showing results for 
Search instead for 
Did you mean: 

Use S3 images just on product page

Use S3 images just on product page

Client wants to use S3 to store main images on the product page, and the gallery images too. Small and thumbnail images are imported but the Product page should get its images from S3 with urls like 

https://bucketname.s3.eu-west-1.amazonaws.com/sku_1.jpg

I have a custom module with the following code but it's not working - I really am not sure what I am doing so maybe the whole idea is wrong or maybe it's just something small. The actual module functionality is working, echo $sku; works. I had a different version before where I didn't use the Aws\ library, just used the image URLs but it was slow so I am looking for alternatives.

 

 

<?php

namespace Modulename\CDNExtraImages\Plugin;

use Magento\Catalog\Block\Product\View\Gallery;
use Magento\Framework\Data\Collection;
use Magento\Framework\Data\CollectionFactory;
use Magento\Framework\DataObject;
use Vendor\AWS; class AddImagesToGalleryBlock { /** * @var CollectionFactory */ protected $dataCollectionFactory; /** * AddImagesToGalleryBlock constructor. * * @param CollectionFactory $dataCollectionFactory */ public function __construct( CollectionFactory $dataCollectionFactory ) { $this->dataCollectionFactory = $dataCollectionFactory; } /** * afterGalleryImages Plugin to change images and use external images stored in custom attribute * * @param Gallery $subject * @param Collection|null $images * @return Collection|null */ public function afterGetGalleryImages(Gallery $subject, $images) { try { $product = $subject->getProduct(); $images = $this->dataCollectionFactory->create(); $productName = $product->getName(); $sku = $product->getSku(); echo $sku; $bucket = 'bucketname'; $credentials = new \Aws\Credentials\Credentials('AWSAccessKeyId', 'AWSSecretKey'); $s3Client = new \Aws\S3\S3Client([ 'region' => 'eu-west-1', 'credentials' => $credentials ]); $externalImages = $s3Client->getIterator('ListObjects', ['Bucket' => $bucket, 'Prefix' => $sku]); foreach ($externalImages as $item) { $fileName = $item['Key']; $modifiedImage = $item['LastModified']; echo $fileName; echo $modifiedImage; var_dump($item); $imageId = uniqid(); $small = $item; $medium = $item; $large = $item; $image = [ 'file' => $large, 'media_type' => 'image', 'value_id' => $imageId, // unique value 'row_id' => $imageId, // unique value 'label' => $productName, 'label_default' => $productName, 'position' => 100, 'position_default' => 100, 'disabled' => 0, 'url' => $large, 'path' => '', 'small_image_url' => $small, 'medium_image_url' => $medium, 'large_image_url' => $large ]; $images->addItem(new DataObject($image)); } return $images; } catch (\Exception $e) { return $images; } } }