Question

I'm starting to learn Magento 2 and I read some instructions to create Controller.

There are the index.php. on Magento 2 _ development cookbook and another on website.

/** @var \Magento\Framework\View\Result\PageFactory  */
       protected $resultPageFactory;
public function __construct( \Magento\Framework\App\Action\Context $context,
           \Magento\Framework\View\Result\PageFactory
$resultPageFactory ){
$this->resultPageFactory = $resultPageFactory;
           parent::__construct($context);
       }
       public function execute()
       {
$resultPage = $this->resultPageFactory->create();
           return $resultPage;
       }

and the another code that I read.

 class Index extends Action
{
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->renderLayout();`

I saw that, two codes are show same layout page Magento. So what does the different between that ?`

Was it helpful?

Solution

General

In Magento 2 all controller actions must return something, opposed to M1, where a controller action would just output something or did a redirect. The result of the execute method from each controller is generated in Magento\Framework\App\FrontController::dispatch() on line $result = $actionInstance->execute(); and returned.

Depending on the type of the returned result a different action is performed. The result can be and instance of :

  • \Magento\Framework\View\Result\Page - actually renders html

  • \Magento\Framework\Controller\Result\Redirect - redirects to an other page

  • \Magento\Framework\Controller\Result\Forward - forwards to an other action (internal redirect)

  • \Magento\Framework\Controller\Result\Json - returns a json object.

  • \Magento\Framework\Controller\Result\Raw - returns whatever you tell it to return (string).

Specific

resultPageFactory is an instance of \Magento\Framework\View\Result\PageFactory and when calling create on that class it returns an instance of \Magento\Framework\View\Result\Page described above. When this is used and the result is returned it means that your action will return HTML. It has somehow a similar effect as $this->loadLayout(); from Magento 1. When you call create on the resultPageFactory object it actually loads the layout.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top