Really quick and simple question but I can't find a decent answer to this - What is the best way to pass data from a controller to a block in Magento.
Incase it makes a difference, I am loading the layout as follows:
$this->loadLayout(array('default', 'myModule_default'));
$this->_initLayoutMessages('customer/session')
->_initLayoutMessages('catalog/session')
->renderLayout();
I should add, that I have been using the registry as follows:
In the controller:
Mage::register('data', $data);
In the block:
$data = Mage::registry('data');
Not sure if this is the best way to do it though.
You don't.
In Magento's MVC approach, it's not the responsibility of the controller to set variables for the view (in Magento's case, the view is Layout and blocks). Controllers set values on Models, and then Blocks read from those same models. In Magento's view of the world, having a Block relying on the controller doing a specific thing is tight coupling, and should be avoided.
Your controller's job is to do certain things to Models, and then tell the system it's layout rendering time. That's it. It's your Layout/Blocks job to display an HTML page in a certain way depending on the state of the system's Models.
So, if I wanted to emulate traditional PHP MVC behaviors I'd
Create a simple Model class the inherits from Varien_Object
In the controller, instantiate that object using the Mage::getSingleton('foo/bar')
Set values on the Model using the magic getter/setters (you get these in objects that inherit from Varien_Object
), or setData
, etc.
In the Blocks, instantiate the Model again with a Mage::getSingleton('foo/bar')
and read the values back.
When you instantiate a Model with Mage::getSingleton(...)
Magento will instantiate the object as a singleton. So, if you re-instantiate an object (again with Mage::getSingleton('foo/bar')
) you're getting back the same object.