Zend Framework 不仅实现了完整的 MVC 结构,而且还提供了与之相辅相成的众多"配件",视图助手 View Helper 就是其中之一。

 

试图助手顾名思义就是帮助视图 view 来完成变现层的工作,它的主要作用有两个,一个是封装 html 代码,另一个是调用 model 整合数据。

 

在这里我将介绍如何创建自己的试图助手,并且以一个有用但却非常简单的助手图片助手 - Image Helper 为例。

 

 

以下是完整的代码:



 

// Bootstrap.php

// 获取 viewRenderer 视图助手
$viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');

// 初始化 view
$viewRenderer->initView($viewBasePath);
$view = $viewRenderer->view;

// 加入自定义 view helper 所在目录路径及前缀
$view->addHelperPath('Kbs/View/Helper/', Kbs_View_Helper_);


 

// 图片助手 : Kbs/View/Helper/Img.php

require_once('Zend/View/Helper/Abstract.php');

class Kbs_View_Helper_Img extends Zend_View_Helper_Abstract
{
public function img($src, $width, $height, $alt = '', $options = array())
{
if (empty($alt)) {
// 为了确保每个图片都是 alt,以优化 SEO
throw new Zend_View_Exception('Alt attribute should be filled.');
}

$basepath = $this->view->serverUrl() . '/public/img/';
$img = '<img src="' . $basepath . $src . '" width="' . $width . '" '
. 'height="' . $height . '" alt="' . $alt . '" />';

return $img;
}
}


 

// index.phtml
echo $this->img('example.jpg', 100, 100, 'This is the example');


 

以上只是很简单的例子,但是已经足够说明 View Helper 的灵活性。