且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Magento-在控制器和块之间传递数据

更新时间:2023-11-30 13:59:28

您没有.

在Magento的MVC方法中,控制器没有责任为视图设置变量(在Magento的情况下,视图是布局和块).控制器在模型上设置值,然后从这些相同的模型读取块.在Magento的世界观中,让Block依赖于控制器来完成特定的事情是紧密耦合的,因此应避免.

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.

您的控制器的工作是对模型进行某些操作,然后告诉系统其布局渲染时间.而已.根据系统模型的状态,以某种方式显示HTML页面是您的Layout/Blocks工作.

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.

因此,如果我想模仿传统的PHP MVC行为,

So, if I wanted to emulate traditional PHP MVC behaviors I'd

  1. 创建一个简单的Model类,该类继承自Varien_Object

在控制器中,使用Mage::getSingleton('foo/bar')

使用神奇的getter/setter(在从Varien_Object继承的对象中获得)或setData等的方式在模型上设置值.

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

在块中,再次使用Mage::getSingleton('foo/bar')实例化模型,然后读回值.

In the Blocks, instantiate the Model again with a Mage::getSingleton('foo/bar') and read the values back.

当您使用Mage::getSingleton(...)实例化模型时,Magento会将对象实例化为单例.因此,如果重新实例化一个对象(再次使用Mage::getSingleton('foo/bar')),则将返回相同的对象.

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.