2012-12-26 55 views
2

我遇到了一個問題,因爲我目前沒有理解該框架的功能。我想設置一個ViewHelper,根據我在哪個網站上返回一個輸出。如果我匹配兩個特定的routeschild_routes,我希望ViewHelper根據該路線輸出鏈接列表。如果我不在這些匹配的路線上,我想輸出什麼。在ViewHelper中訪問路由器以匹配路由或child_routes

建立一個視圖助手是相當簡單的,現在我的視圖助手看起來是這樣的:

'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部分需要變化。它應該是foobarfoobar可以有child_routesfoo/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"; 
} 
+0

你試圖顯示替代路線匹配(如果有的話)? – yechabbi

+0

通過上面的例子,我希望URL'someLink'可以是'foo/sub'或'bar/sub',具體取決於if'foo'或'bar'或任何給定的child_route。爲此,我需要將匹配的路由注入到視圖助手中。我的問題是,我如何才能找到當前匹配的路線。 – Sam

回答

3

您可以在視圖助手定義一個方法,它假定您可以訪問到服務管理。以下是實現你的問題的解決方案的一種方式:

//$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); 
+0

非常感謝,這對我有很大的幫助。從'$ routeName'我只需要用'/'分解它,並使用jey'[0]'作爲父路由名,這正是我想要的。萬分感謝! – Sam

+0

不客氣。 – yechabbi

1

沒有新的比賽的另一個解決方案

$ serviceLocator-> GET( '應用') - > getMvcEvent() - > getRouteMatch() ;