【发布时间】: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