【问题标题】:Need help figuring out how to write my zend view helper需要帮助弄清楚如何编写我的 zend 视图助手
【发布时间】:2010-08-03 15:14:15
【问题描述】:

总的来说,我对 Zend Framework 和 MVC 还很陌生,所以我正在寻找一些建议。我们有一个基本控制器类,其中我们有一些方法来获取一些用户信息、帐户配置等。

所以我使用其中一些方法在各种控制器操作中写出代码,但现在我想避免重复此代码,而且我想将此代码放在控制器之外并在视图助手中作为主要是输出一些JavaScript。所以控制器中的代码如下所示:

$obj= new SomeModel ( $this->_getModelConfig () );
$states = $obj->fetchByUser ( $this->user->getId() );
//Fair amount of logic here using this result to prepare some javascript that should be sent to the view...

$this->_getModelConfig 和 $this->user->getId() 是我可以在控制器中做的事情,现在我的问题是,一旦我移动,将这些信息传递给视图助手的最佳方式是什么这段代码脱离了控制器?

我是否应该在控制器中调用这些方法并将结果存储到视图中并让助手从那里获取它?

我正在考虑的另一个选项是向帮助程序添加一些参数,如果传递了参数,那么我将它们存储在帮助程序的属性中并返回,当在不传递参数的情况下调用它时,它会执行工作。所以它看起来像这样:

来自控制器:

$this->view->myHelper($this->user->getId(), $this->_getModelConfig());

从视图:

<?= $this->myHelper(); %>

助手:

class Zend_View_Helper_MyHelper extends Zend_View_Helper_Abstract
{
    public $userId = '';
    public $config = null;
    public function myHelper ($userId = null, $config = null)
    {
        if ($userId) {
            $this->userId = $userId;
            $this->config = $config;
        } else {
            //do the work
            $obj = new SomeModel($this->config);
            $states = $obj->fetchByUser($this->userId);
            //do the work here  
        }
        return $this;
    }
}

欢迎任何建议!

【问题讨论】:

    标签: model-view-controller zend-framework zend-view view-helpers


    【解决方案1】:

    首先,“$this->myHelper(); %>”处的 ASP 样式结束标记是不好的做法,也就是说,最好将逻辑保留在模型中,而控制器仅用于调用模型,获取结果并将其吐到视图中以供查看。

    我要做的是,如果我只是想将一堆值传递给视图,我会将它们填充到一个关联数组中并发送过来。

    无论如何你不应该做你的......

    "//这里有相当数量的逻辑使用这个结果来准备一些应该发送到视图的 javascript..."

    在控制器中的一部分,我建议你创建一个新模型来为你做这些逻辑的东西,你只需在控制器中调用你的模型,将所需的参数传递给它,然后将结果吐给视图。

    【讨论】:

    • 我的问题就是将该代码从控制器中取出。我不想做的是让我的模型输出
    【解决方案2】:

    最好的方法是通过控制器从模型中获取数据,然后传递给视图。但是如果你真的需要一个自定义助手来回显视图部分,我们只会知道你是否准确地说出你想要做什么。

    如果您已经在帮助程序中具有此逻辑,请尝试仅在视图中传递参数 myhelper($this->params); ?>

    您可能也想看看这种方法:

    // In your view to put javascript in the header
    // You can loop trought your data and then use it to generate the javascript.
    <?php $this->headScript()->captureStart(); ?>
        $().ready(function(){
            $('#slideshow').cycle({ 
                fx:     'fade', 
                speed:  1000, 
                timeout: 6500, 
                pager:  '#nav'
            });
        });
    <?php $this->headScript()->captureEnd() ?>  
    

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      相关资源
      最近更新 更多