一般来说,我对 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;
}
}
欢迎任何建议!