创建一个简单的视图(模板)插件

http://helion.name/archives/481.html#more-481

这篇文章将向你讲诉如何在ZF2中添加一个简单的视图插件

在下面的例子中,我们的视图插件将返回一个当前页面的完整URL,我们还是已先前的album为基础框架.

首先在album的src下面添加路径”View\Helper\“在上面的路径下新建一个文件,命名为”AbsoluteUrl.php“,代码如下:

<?php
// ./module/Album/src/Album/View/Helper/AbsoluteUrl.php
namespace Album\View\Helper;
 
use Zend\Http\Request;
use Zend\View\Helper\AbstractHelper;
 
class AbsoluteUrl extends AbstractHelper
{
    protected $request;
 
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
 
    public function __invoke()
    {
        return $this->request->getUri()->normalize();
    }
}

在这里我们用到了一个依赖:Zend\Http\Request,为了注入这个依赖,在视图初始时,要进行初始化, 在album的Module.php文件添加下面的代码:

<?php
// ./module/Album/Module.php
namespace Album;
use Album\View\Helper\AbsoluteUrl;
class Module
{
    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                // the array key here is the name you will call the view helper by in your view scripts
                'absoluteUrl' => function($sm) {
                    $locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
                    return new AbsoluteUrl($locator->get('Request'));
                },
            ),
        );
    } 
}
在你的index.phtml里面添加:

The full URL to the current page is: <?php echo $this->absoluteUrl(); ?>
运行一下,看是不是打印出完整的网址了?


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值