Magento 2 Dependency Injection – Use a Model with a Dynamic Name

dependency-injectionmagento2model

I have a M1 module that I'm looking at porting to M2, and part of one of helpers contains code that looks like this:

public function getModel($code)
{
     return Mage::getSingleton('vendor/package_model_' . $code);
}

Given that Magento 2 uses dependency injection, I know that I can specify that I'd like an instance of \Vendor\Package\Model\Interface, but how can I specify that I'd like a specific model?

I'd like to follow best practice, so if it's possible to avoid doing this directly through the ObjectMananger then that would be ideal, but if that's the only option then that's OK too.

Best Answer

Try to get rid of this shortcut method and use dependency injection to get the actual classes you need where you previously used this.

Related Topic