In Magento 1, if you want to pass data from your Controller action to the "View" (i.e. a block in your layout, you can)
Add a value/object to the global registry via
Mage::register
Directly fetch a block object and set data properties on the fetched block object after running
loadLayout
Call methods on block objects in
phtml
files, and have the block objects use the model/database layer to read data previously saved in the controller action
Using block object methods to read from the database still appears to work in Magento 2 -- which is appropriate for certain sorts of operations. However,
There's no longer a global registry in Magento 2 (or is there?)
The layout system now works by creating a page object via a factory, and you can't grab block references the same way you can in Magento 1
Is it possible in Magento 2 to pass data directly from a controller action down to a view? Or is this too direct a pattern for Magento's brave new Design Pattern™ world? If this is too direct a pattern, what should be doing if there's some calculated information we want to display in a template, but don't want to store that information into a stateful system (i.e. we don't want to save it to the database)
I can think of a few different way to hack this together myself -- but I'm interested in how Magento 2 wants you to do it.
Note: I realize it's possible to fetch a block instance in a controller action using something like this
$resultPage = $this->resultPageFactory->create();
$block = $resultPage->getLayout()->getBlock('catalog.wysiwyg.js');
var_dump(spl_object_hash($block));
The Magento 2 core code does this often. However -- the block object fetched in the controller object seems to be a different object than is available in a phtml
template via either $this
or $block
(the former ($this
) appears to be the object that actually renders the template, whereas the later ($block
) appears to be an instance of the Magento Block type).
#File: path/to/template.phtml
var_dump(spl_object_hash($block));
var_dump(spl_object_hash($this));
I say "appears to be" because if I set data in the controller action method, it's not available in the phtml
template -- and if I compare the spl_object_hash
results above, I get three different hashes. However, I'm new enough to all this that the above might be some other error I've made -- so if you've been able to set data on blocks and fetch it in a template I'd love to hear about it!