Magento – Passing data between a controller and a block

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

  1. Create a simple Model class the inherits from Varien_Object

  2. In the controller, instantiate that object using the Mage::getSingleton('foo/bar')

  3. Set values on the Model using the magic getter/setters (you get these in objects that inherit from Varien_Object), or setData, etc.

  4. 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.

Leave a Comment