在ZF2的视图文件中,我们可以很方便的使用$this->escapehtml()等方法。
那么我们怎么样来自定义的这种方法呢?
需求:某网站的图片储存在不同的服务器中,每次都要在视图文件中填写完整的URL信息,我们可以建立自己的视图助手来帮助我们完成这些操作。
Step 1: 建立我们的图片服务器配置信息
在global.php中添加自定义配置信息:
return array( ... 'img_service' =>array( 'face' => 'http://face.img.mushroot.com/', 'article' => 'http://article.img.mushroot.com/', ), ... );
Step 2: 建立自己的视图助手(ImgService)
(path: /module/Application/src/Application/View/Helper/ImgService.php)
<?php /** * 图片服务器视图助手 * * @author Star <wmistar@gmail.com> * @license http://mushroot.com * @version: 1.0 * */ namespace Application\View\Helper; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\View\Helper\AbstractHelper; class ImgService extends AbstractHelper { protected $config; public function __construct(ServiceLocatorInterface $sm) { $this->config = $sm->getServiceLocator()->get('config'); } public function __invoke($conf = '') { $imgservice = $this->config['img_service']; switch ($conf){ case 'face' : $res = $imgservice['url']; break; case article : $res = $imgservice['city']; break; default: $res = ''; break; } return $res; } }
Step 3: 在Module中调用视图助手配置
<?php /** * Application 模块管理器 * * @author Star <wmistar@gmail.com> * @license http://mushroot.com * @version: 1.0 * */ namespace Application; use Zend\ModuleManager\Feature\ConfigProviderInterface; use Zend\ModuleManager\Feature\AutoloaderProviderInterface; use Zend\ModuleManager\Feature\ViewHelperProviderInterface; use Application\View\Helper\ImgService; class Module implements ConfigProviderInterface, AutoloaderProviderInterface, ViewHelperProviderInterface { ... public function getViewHelperConfig() { return array( 'factories' => array( 'imgService' => function($sm) { return new ImgService($sm); }, ) ); } ... }
Step 4: 在视图文件中使用自定义视图助手
例如在index.phtml中
<?php echo $this->imgService('face') . '1.png'; //output 'http://face.img.mushroot.com/1.png' ?> 转自http://mushroot.com/zf2-zend-framework-2-rumen-zidingyishituzhushou-view-helper#more-298