浏览文章
文章信息
【Magento2】让我们来解决一个rest api产品图片找不到的问题
12251
/** * @Api * @Desc | 搜索 * @param string $words * @param int $page * @param int $pageSize * @return mixed */ public function search(string $words,int $page,int $pageSize) { $page = $page ?? 1; $pageSize = $pageSize ?? 10; $storeId = $this->storeManager->getStore()->getId(); // 仿真环境 开始 $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true); /**@var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */ $collection = $this->productCollectionFactory->create(); $items = $collection->addStoreFilter($storeId) ->addAttributeToSelect('*') ->addAttributeToFilter('name',['like'=>"%{$words}%"]) ->addAttributeToFilter('sku',['like'=>"%{$words}%"]) ->setCurPage($page) ->setPageSize($pageSize) ->getItems(); $tmp = []; foreach ($items as $item) { $imageUrl = $this->imageHelperFactory->create() ->init($item, 'product_thumbnail_image')->getUrl(); $item->setData('image',$imageUrl); $tmp[] = $item->getData(); } // 仿真环境 结束 $this->appEmulation->stopEnvironmentEmulation(); return [ 'words' => $words, 'data' => $tmp, 'pagination' => [ 'page' => $page, 'pageSize' => $pageSize ]]; }
使用Magento的仿真环境,我们获取PC的产品图。
// 仿真环境 开始 $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);// 仿真环境 结束 $this->appEmulation->stopEnvironmentEmulation();这两句我们仿真了PC前端的环境,所以我们拿到了PC的产品图片。
此方法有待商榷!慎用哈。我正在找api图片获取!