What is the purpose of rendering the custom module page in Magento2 using the result factory \Magento\Framework\View\Result\PageFactory
class injected in the constructor and making the page to display
$resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
rather than doing these below kind of display which is same like in Magento 1.x approach
$this->_view->loadLayout();
$this->_view->renderLayout();
Best Answer
Actually is not necessary to return an instance of
\Magento\Framework\View\Result\Page
. Theexecute
is expected to return an instance of a class that implements the interface\Magento\Framework\Controller\ResultInterface
.\Magento\Framework\View\Result\Page
is just one possible return.Other possible returns are
\Magento\Framework\Controller\Result\Redirect
\Magento\Framework\Controller\Result\Raw
\Magento\Framework\View\Result\Layout
\Magento\Framework\Controller\Result\Forward
\Magento\Framework\Controller\Result\Json
and there may be others.
take a look at the method
Magento\Framework\App\Action\Action::dispatch()
.This should return an instance of
\Magento\Framework\Controller\ResultInterface
and based on the result different actions are taken, again by calling methods declared in theResultInterface
.This
dispatch
method calls$result = $this->execute();
which is theexecute
method from the controller action. So I guess this is for consistency and to make it easier to introduce a different behavior for a controller action. You just need to add a new class that implementsResultInterface
and it will all be handled by the framework.