如何在视图中使用zf2 hasRoute()

时间:2015-01-17 23:20:49

标签: view routes zend-framework2

我正在尝试开发一个使用以下内容呈现链接的索引视图:

echo "<a href=";
echo $this->url($route, array('action' => $action, 'id' =>$id));
echo ">$targetName</a>";

其中$route$action$id$targetName均来自数据库。

我不能依赖$route变量的数据,当$route与可行路线不匹配时,整个页面崩溃。我想使用if语句来评估路由的存在,但我找不到正确的解决方案。我想我正在寻找类似的东西:

if ( hasRoute($this->url($route, array('action' => $action, 'id' =>$id))) ) {
   // render something
} else {
  // render something different
}

但是,我无法通过阅读文档来确定如何正确使用hasRoute()功能。上面的简单代码会导致Fatal error: Call to undefined function hasRoute()

1 个答案:

答案 0 :(得分:3)

Zend Framework中没有hasRoute视图助手,但您可以创建一个(documentation)。

首先,您需要创建视图助手类,其中路由器为依赖项:

<?php
// file module/Application/View/Helper/HasRoute.php

namespace Application\View\Helper;

use Zend\Mvc\Router\SimpleRouteStack;
use Zend\View\Helper\AbstractHelper;

final class HasRoute extends AbstractHelper
{
    /** @var SimpleRouteStack */
    private $router;

    /**
     * @param SimpleRouteStack $router
     */
    public function __construct(SimpleRouteStack $router)
    {
        $this->router = $router;
    }

    /**
     * @param string $routeName
     * @return bool
     */
    public function __invoke($routeName)
    {
        return $this->router->hasRoute($routeName);
    }
}

然后你需要一个这个视图助手的工厂,它创建我们帮助器的新实例并注入路由器:

<?php
// file module/Application/Factory/View/Helper/HasRouteFactory.php

namespace Application\Factory\View\Helper;

use Application\View\Helper\HasRoute;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class HasRouteFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return HasRoute
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $router = $serviceLocator->getServiceLocator()->get('router');

        return new HasRoute($router);
    }
}

最后你需要注册这个新的视图帮助器来查看帮助器插件管理器:

// Application module configuration file in module/Application/config/module.config.php
// ...
'view_helpers' => [
    'factories' => [
        'hasRoute' => \Application\Factory\View\Helper\HasRouteFactory::class,
    ],
],
// ...

然后,您可以在任何模板中调用此视图助手:

<?php
    if ($this->hasRoute('home')) {
        // do something if there is route with name 'home' defined
    }
?>