Thanks to Magento 2’s MVVM approach the traditional responsibilities of a controller object have been pushed into the “view model” layer (i.e. a block’s _prepareLayout
method).
The main job a controller performs in Magento 2 is to
- Determine what sort of response is needed (HTML page, JSON, Redirect)
- Create an object to handle that response
- Return that object to the system for processing
For a standard HTML page, this means injecting a page factory object in your controller’s constructor
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
}
and using that factory to return an object in the controller’s execute
method.
$resultPage = $this->resultPageFactory->create();
return $resultPage;
One benefit of this is, it’s pretty easy to add custom layout handles to your response. Every page object has an addHandle
method
$resultPage = $this->resultPageFactory->create();
$resultPage->addHandle('my_custom_handle');
return $resultPage;
and your response will include the additional handle. This was possible in Magento 1, but required redefining a specific controller action method in your controller, and making sure you included a call to the parent method. It’s not an earth shattering improvement, but its something that makes life a little easier for module developers.