Emulate store in Magento

Magento 1.5 introduced very interesting piece of code that enables easy store emulation when programming, Emulation model a.k.a. Mage_Core_Model_App_Emulation class.
This is how it’s done:
$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);
First time I needed something similar was when I wanted to send custom transactional e-mail for all stores at the same time as cronjob. However, the problem was that e-mail had {{block}} inside and block template needed to respect different theme set for each store. Lets say the code was something like:
foreach(Mage::app()->getStores() as $store) {
$dummyModel->setStore($store);
$dummyModel->sendEmail();
}
If block template was at email/custom-email-block.phtml, email sent from first store needs to grab
app/design/frontend/default/store1_theme/template/email/custom-email-block.phtml, second one
app/design/frontend/default/store2_theme/template/email/custom-email-block.phtml and so on ..
With new Emulation model this is really simple task.
Magento implemented Emulation model for the same reason. Usage example can be seen when ProductAlert is sending email for all Magento websites at the same time, also cronjob, or in order/invoice/creditmemo e-mail sending because those e-mails are sent from administration, so no real store is set. We need to emulate the store in which order is created.
Anyway, topic was interesting enough for me to write this article 🙂
3 comments
Does this store emulation apply to controllers? For instance, if I want to emulate Mage_Customer and use the setCustomerAsLoggedIn($user) method, will the Mage_Log catch the event? I spent a long hard time recreating this functionality. See here:
http://stackoverflow.com/questions/14201677/how-can-i-trigger-controllerless-core-magento-modules-that-watch-controller-act
I have checked that many recent issues are solved in Magento 1.6. Still, i am wondering whether edit orders is in Magento road-map or not. Wasting db space with lots of cancelled orders is something which is not good for optimization and in longer run it will slow the store down.
magento 1.5 has some great improve i like very much. by the way, the picture has a fuzziness show .