我遇到了一个问题,目前我对框架的功能不了解。我想设置一个 ViewHelper
,它根据我所在的站点返回输出。如果我匹配两个特定的routes
或child_routes
,我希望ViewHelper根据该路由输出链接列表。如果我不在那些匹配的路线上,我不想输出任何内容。
设置 ViewHelper 非常简单,现在我的 ViewHelper 看起来像这样:
'factories' => array(
'myViewHelper' => function($sm) {
$service = $sm->getServiceLocator()->get('some-doctrine-entity');
return new \Mynamespace\View\Helper\ViewHelper($service);
}
)
输出是一个类似的链接列表
$this->url('someLink', array('id', $service->getId());
现在我的问题是 someLink
部分需要是可变的。它应该是 foo
或 bar
。 foo
和 bar
都可以有 child_routes
像 foo/index, foo/details, foo/etc
我需要匹配所有这些。
所以我的问题是如何写这个
$currentRoute = somehowGetTheCurrentRoute();
if ($currentRoute matching `foo` or `foo/child_routes`
or is matching `bar` or `bar/child_routes`) {
echo "im happy";
}
最佳答案
您可以在 View 助手上定义一个方法,它假设您有权访问服务管理器。以下是解决您的问题的方法:
//$sm is the service manager
$router=$sm->get('Router');
$request=$sm->get('Request');
$routeMatch=$router->match($request);
//get an array of the route params and their values
$routeparams=$routeMatch->getParams();
//get the matched route name
$routename=$routeMatch->getMatchedRouteName();
//The previous parameters can be injected directly into the url plugin call
//$this->url($routename,$routeparams)
//the full path can also be obtained from the router
//(you can test it within a controller)
$path=$router->assemble($routeparams,$options);
关于routes - 在 ViewHelper 中访问路由器以匹配路由或 child_routes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14047043/