Magento-在控制器和块之间传递数据 [英] Magento - Passing data between a controller and a block

查看:85
本文介绍了Magento-在控制器和块之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确实是一个快速而简单的问题,但我对此找不到合适的答案-将数据从控制器传递到Magento中的块的最佳方法是什么.

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:

在控制器中:

Mage::register('data', $data);

在区块中:

$data = Mage::registry('data');

虽然不确定这是否是最好的方法.

Not sure if this is the best way to do it though.

推荐答案

您没有.

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

这篇关于Magento-在控制器和块之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆