Magento – Magento 2 – how to get custom model from custom module

custommagento2modelmodule

In Magento 2, how can I get a custom model that is created in a custom module (not a Magento 2 native module)? I know I can use object manager for getting and creating, and I know how to do this for Magento models, for example, to get the Mage::getModel('sales/order') I can use: $om->get('Magento\Sales\Model\Order'). How can I get a custom model "custom model" created in module "module-name"?

Best Answer

You can get the model by injecting it into the constructor.

like :

if your model is

vendor_name\module_name\Model\CustomModel

You should use inject in the constructor like

public function __construct(
    <vendor_name>\<module_name>\Model\CustomModelFactory $customModelFactory
) {
    $this->customModelFactory = $customModelFactory;
}

now you can get customModel object by using $this->customModelFactory->create().

But the more appropriate way to access a model is by using a repository.

So follow the repository pattern Magento 2 follows and then inject the repository in the constructor.

Now using the repository you can get a model.

For more info on the repository, pattern refer: http://alanstorm.com/magento_2_understanding_object_repositories/

Related Topic