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(); ?>
运行一下,看是不是打印出完整的网址了?