Reading list Switch to dark mode

    Magento2 Store Emulation

    Updated 6 March 2024

    In a system like Magento2, it’s quite difficult to handle some situation while coding like updating the data according to correct scope, people end up with the ideas like changing the store scope by using setCurrentStoreId()  method like below:

    $currentStoreId = $this->_storeManager->getStore()->getId();
    // Magento\Store\Model\StoreManagerInterface
    $this->_storeManager->setCurrentStoreId($storeId);
    
    // ...
    // your code 
    // ....
    
    $this->_storeManager->setCurrentStoreId($currentStoreId);

    and then after doing their work again setting that value back to the old one, but this is not the efficient way since there can be many other things that you need to change to create the store’s environment, so changing them like that does not seem a better solution, that’s why Magento has provided a class to do such things, \Magento\Store\Model\App\Emulation this class provides two methods:

    • startEnvironmentEmulation($storeId, $area= \Magento\Framework\App\Area::AREA_FRONTEND, $force=false)
    • stopEnvironmentEmulation()

    An example of how we can use these methods to emulate the store environment:

    /**
      * \Magento\Store\Model\App\Emulation
      */
     protected $emulation;
    
    public function __construct(\Magento\Store\Model\App\Emulation $emulation) {
       $this->emulation = $emulation;
    }
    
    /**
     * example function in which we want to emulate a stores environment  
     */
    public function example($storeId, $area = 'frontend') {
      
       //starting the store emulation with area defined for admin
       $this->emulation->startEnvironmentEmulation($storeId, 'adminhtml');
       
       //you can update or save a product attributes here with correct scope or anything else you want to do, perform some test
       
       // discard the emulated environment after doing your work
       $this->emulation->stopEnvironmentEmulation();
       
    }

    Hope this blog will help you in better code implementation. Feel free to ask your doubts in the comment.

    Thanks

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • ashutosh srivastava (Moderator)
  • Suman
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home