20

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();

2 Answers 2

16

Actually is not necessary to return an instance of \Magento\Framework\View\Result\Page. The execute 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 the ResultInterface.
This dispatch method calls $result = $this->execute(); which is the execute 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 implements ResultInterface and it will all be handled by the framework.

3

I believe that idea was return data/models from controllers, but current implementation looks strange for me too.

Personally I expect to that controllers do not return anything, maybe just redirect to other url. To page layout need adds route on with this page will be available.

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-login">
     <route url="login"/>
    <body>
    </body>
</page>

JSON will available from rest api

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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