Magento替代setCurrentStore()

Bob*_*ijt 3 magento

我的Observer文件夹中有一个公共函数.(我使用它来浏览图像)但问题是,我不想使用'Mage :: app() - > 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++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mol*_*iel 11

我认为这是因为您退出函数时不会将商店更改回默认值.但更好的解决方案是使用仿真环境:

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);
}
Run Code Online (Sandbox Code Playgroud)

环境仿真之间的所有代码都将像magento设置所需的商店一样,外部应该正常工作.

另请注意,您的代码可能会抛出异常,因此,您应该使用try catch语句,以确保每次都会执行停止环境仿真的函数的最后一行.


ben*_*rks 6

您可以使用仿真.来自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);
Run Code Online (Sandbox Code Playgroud)

我想指出,当你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
    }
}
Run Code Online (Sandbox Code Playgroud)