2013-02-24 140 views
2

我在我的Observer文件夾中有一個公共功能。 (我用它來瀏覽圖像),但事情是,我不想使用'法師:: app() - > setCurrentStore()'Magento替代setCurrentStore()

什麼是替代瀏覽給定商店沒有使用setCurrentStore()?

function getImages($store, $v){ 
    Mage::app()->setCurrentStore($store); 
    $products = Mage::getModel('catalog/product')->getCollection(); 
    $products->addAttributeToSelect('name'); 
    foreach($products as $product) { 
     $images = Mage::getModel('catalog/product')->load($product->getId())->getMediaGalleryImages(); 
     if($images){  
      $i2=0; foreach($images as $image){ $i2++; 
       $curr = Mage::helper('catalog/image')->init($product, 'image', $image->getFile())->resize(265).'<br>'; 
      } 
     } 
    } 
} 

foreach (Mage::app()->getWebsites() as $website) { 
    foreach ($website->getGroups() as $group) { 
     $stores = $group->getStores(); 
     foreach ($stores as $store) { 
      getImages($store, $i); 
      $i++; 
     } 
    } 
} 

PS: 如果我使用setCurrentStore()我的管理員搞砸了:-S

回答

9

我想這是因爲你不改變商店回到默認,當你從你的函數退出。 但是一個更好的解決方案是使用仿真環境:

function getImages($store, $v){ 
    $appEmulation = Mage::getSingleton('core/app_emulation'); 
    $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId); 
    //if $store is a model you can use $store->getId() to replace $storeId 
    try { 
     //your function code here 
    catch(Exception $e){ 
     // handle exception code here 
    } 
    $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); 
} 

所有環境仿真的代碼將作爲像的Magento已經設置所需的存儲和外部的一切都應該正常工作。

另請注意,您的代碼可能會引發異常,因此您應該使用try catch語句以確保每次都會執行停止環境仿真的函數的最後一行。

+0

太棒了,這就是我一直在尋找的! – 2013-02-24 19:44:12

+1

額外的好處:這模擬了前端 - 這意味着你在它內部使用的所有相關引用(例如,任何皮膚或設計文件,如css,phtml,js等)都是相對於前端根目錄的 - 所以你可以使用在BACKEND上顯示app_emulation,以顯示通常只在FRONTEND – Benubird 2013-03-28 09:31:42

+0

可見的塊。感謝它的運作。你是一個拯救生命的人:) – deanpodgornik 2015-02-26 14:38:51

5

您可以使用仿真此。從http://inchoo.net/ecommerce/magento/emulate-store-in-magento/

$appEmulation = Mage::getSingleton('core/app_emulation'); 
//Start environment emulation of the specified store 
$initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId); 
/* 
* Any code thrown here will be executed as we are currently running that store 
* with applied locale, design and similar 
*/ 
//Stop environment emulation and restore original store 
$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); 

我想指出的是,你是一個資源昂貴的決定,當你在收集迭代調用load()。給定你的目錄大小和運行上下文可能沒問題,但是你可以通過調用$products->addAttributeToSelect('*')來完成同樣的操作,而不用顛簸你的數據庫。這將抓住所有的屬性和值;鑑於目前的情況下,你可以得到你所需要的,如下所示:

$products = Mage::getModel('catalog/product')->getCollection(); 
$products->addAttributeToSelect('name') 
     ->addAttributeToSelect('media_gallery'); 
foreach($products as $product) { 
    $images = $product->getMediaGalleryImages(); 
    if($images){ 
     // your logic/needs 
    } 
}