How to instantiate a model in Magento 2
Since Magento strictly discourages the use of ObjectManager, there are service classes for abstracting it for all scenarios. Thus, you should use factory for all models (non-injectables):
1 2 3 4 5 6 7 8 9 10 11 12 13 |
protected $pageFactory; public function __construct(\Magento\Cms\Model\PageFactory $pageFactory) { $this->pageFactory = $pageFactory; } public function someFunc() { ... $page = $this->pageFactory->create(); ... } |
You only have to ask a desired model’s factory in a constructor. Hence, it will be automatically generated, while you run compiler or Magento. Continue Reading