Sam
Sam

Reputation: 16455

Accessing router in ViewHelper to match routes or child_routes

I am encountering a problem for which i have no understanding of the function of the framework currently. I want to set up a ViewHelper that returns an output depending on which site i am on. If i match two specific routes or child_routes, i want the ViewHelper to output a list of links depending on that route. If i'm not on those matched routes, i want to output nothing.

Setting up a ViewHelper is pretty simply, right now my ViewHelper looks like this:

'factories' => array(
    'myViewHelper' => function($sm) {
        $service = $sm->getServiceLocator()->get('some-doctrine-entity');
        return new \Mynamespace\View\Helper\ViewHelper($service);
    }
)

The output is a LIST of Links alike that

$this->url('someLink', array('id', $service->getId());

Now my problem is the someLink parts needs to be variable. It should be either foo or bar. Both foo and bar can have child_routes like foo/index, foo/details, foo/etc and i need to match all of them.

So my question is how to write this

$currentRoute = somehowGetTheCurrentRoute();
if ($currentRoute matching `foo` or `foo/child_routes`
  or is matching `bar` or `bar/child_routes`) {
    echo "im happy";
}

Upvotes: 2

Views: 1301

Answers (2)

MarkusM
MarkusM

Reputation: 321

Another solution without a new match

$serviceLocator->get('Application')->getMvcEvent()->getRouteMatch();

Upvotes: 1

yechabbi
yechabbi

Reputation: 1881

You can define a method on your view helper, it assumes you have access to the service manager. The following is a way of achieving a solution of your problem:

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

Upvotes: 3

Related Questions