【问题标题】:How are action methods within Magento layout xml files intended to be used如何使用 Magento 布局 xml 文件中的操作方法
【发布时间】:2012-11-25 04:41:54
【问题描述】:

示例

mylayoutfile.xml

 <layout>
        <default>
            <reference name="header">
                <block type="mynamespace_mymodule/view" name="mynamespace_mymodule" output="toHtml" template="mymodule/html/view.phtml">
                    <action method="setTest"><param1>myparam1</param1><param2>myparam2</param2></action>
                </block>
            </reference>
        </default>
    </layout>

app/code/local/Mynamespace/Mymodule/Block/View.php

    class Mynamespace_Mymodule_Block_View extends Mage_Core_Block_Template{
        public $test = "before any params";
            public function setTest($passedparam1,$passedparam2){
             $this->test = $passedparam1 ." ". $passedparam2;
            }

}

app/design/.../.../mymodule/html/view.phtml

<?php
echo "<pre>";
print_r($this->test);  //myparam1 myparam2
echo"</pre>";
die();

说明

mylayoutfile 是通过您的模块 config.xml 在更新中编译的

mynamespace_module 的块类前缀也在你的模块 config.xml 中定义

mynamespace_module/view 设置为块类型并实例化,并设置 view.phtml 的输出文件

发生了一个调用父节点块的方法 setTest 的操作,传递了两个参数,其值为 myparam1 和 myparam2。

在 setTest 函数内部,类参数“test”设置为等于“myparam1 myparam2”

模板文件 app/design/.../.../mymodule/html/view.phtml 被加载,我们回显 $this->test 的值($this 指的是之前实例化的块类 Mynamespace_mymodule_Block_View)

问题

  1. 有哪些可能使用此功能的用例示例?
  2. 你能传递字符串以外的任何东西吗? (对象,数组)?
  3. 自动设置器和获取器方法是否在布局文件中工作?
  4. 可以使用逻辑(if、then、foreach、else 等)吗?
  5. 是否有不应该使用这种方法的场景?
  6. 我是否还缺少与布局文件中的块实例化相关的其他内容?
  7. 我可能还缺少与布局文件中的操作相关的其他内容吗?

【问题讨论】:

    标签: php xml magento block


    【解决方案1】:
    1. 可用于多用途模板。查看 catalog.xmlsetTitle 的使用。
    2. 任何东西都可以通过。数组可以在布局 XML 中定义:

      <action method="setFoo">
          <arbitrary>
              <key1>val1</key1>
              <key2>val1</key2>
          </arbitrary>
      </action>
      

      另外,参数节点可以执行辅助方法,其返回值将作为值传入:

      <action method="setFoo">
          <arbitrary helper="foo/bar" />
      </action>
      

      这将实例化一个助手并运行一个方法:Mage::helper('foo')-&gt;bar()。因此,返回值可以是您想要的任何值。此外,可以将 args 传递给子节点中的助手!

    3. 块扩展 Varien_Object,所以是的,尽管 setter 是唯一合理的使用方法。
    4. 对此没有直接的逻辑。最接近的是动作的 ifconfig 属性,它将使用提供的参数调用 Mage::getStoreConfigFlag() 并在配置值为 true 时处理动作。
    5. “[c] 不能使用”- 不。 “没关系” - 是的。
    6. 有很多细微差别(这里太多了),但您已经掌握了很多。 Alan Storm 在他的书中得到了所有的细微差别,No Frills Magento Layout;不过,没有什么比自己探索极限更好的了。

    【讨论】:

    • 拿起书,好好读谢谢本。也很好的回答。基本上,您可以从布局中调用堆栈中的任何方法,这是设计系统的一种非常酷的方法。对框架有更多了解,没有必要将任何逻辑放入布局中。您可以直接通过模块加载块,也可以从布局中调用一个方法来计算逻辑并吐出块/更改注册表值/更改对象参数等。
    • 本,我有一个关于类似主题的问题。我需要在管理面板中设置一个变量。即 Name me different
    • @Rob 你需要创建一个助手来从存储中读取值。
    • @benmarks 我从没想过这样处理这个问题!谢谢,我会尝试一下。
    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2013-03-23
    • 2017-04-15
    • 2013-02-08
    • 2012-08-03
    • 1970-01-01
    相关资源
    最近更新 更多