2

I want to write a plugin which executes a code only if a specific store view is active. I have read in the magento docs, that __construct is not allowed in plugins. How can I get the store view in a plugin?

  • 1
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface'); $currentStore = $storeManager->getStore(); $storeId = $storeManager->getStore()->getId(); // Store Id Works? – Ankit Shah Oct 11 '16 at 8:00
  • Thanks for your comment, I used the solution from below, without ObjectManager. – ps202 Oct 11 '16 at 20:58
10

I think you misread the documentation. Basically the following are plugins limitations:

  • Objects that are instantiated before Magento\Framework\Interception is bootstrapped
  • Final methods
  • Final classes
  • Any class that contains at least one final public method
  • Non-public methods
  • Class methods (such as static methods)
  • __construct
  • Virtual types

That does not mean you cannot use __construct() in your plugin class, that means you cannot create a plugin ON a __construct() method.

To answer your question, you can inject the following in your constructor to get the store view:

protected $_storeManagerInterface;

public function __construct(...
     \Magento\Store\Model\StoreManagerInterf‌​ace $storeManagerInterface
    ...)
{
    $this->_storeManagerInterface = $storeManagerInterface;
    ...
}

Then in your code you can do:

$currentStore = $this->_storeManagerInterface->getStore();
$currentStoreId = $currentStore->getId();
  • Oh, thanks... Seems like I misunderstood something... – ps202 Oct 11 '16 at 8:11
  • I get [ReflectionException] Class Magento\Store\Model\StoreManagerInterf‌​ace does not exist – Mohammed Gomma Jan 25 '17 at 9:11
  • @MohammedGomma you probably forgot the first backslash – Raphael at Digital Pianism Jan 25 '17 at 9:14
  • I did it as your example exactly – Mohammed Gomma Jan 25 '17 at 10:53
  • @MohammedGomma try to flush var/di – Raphael at Digital Pianism Jan 25 '17 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.