Zend Framework 2 入门-自定义视图助手(View-Helper)

在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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值