Reputation: 2600
I am trying to setup routing for our ZF2 application.
We have URLS like this:
/foo/bar.json >>> should call /Controller/Foo/BarController.php
/foo/bar/123.json >>> should call /Controller/Foo/BarController.php
/foo/baz/bar.json >>> should call /Controller/FooController.php
and the underlaying controller structure
/Controller/Foo/BarController.php
/Controller/FooController.php
It should route by looking up in the directory structure. So /foo/baz/bar.json
should look
if /Controller/Foo/Baz/BarController.php
exists. If not, look if /Controller/Foo/BazController.php
exists, else look for /Controller/FooController.php
and else give a 404
However i do not seem to get mutch useful information from the zend documentation. I looked at the existing routers but it does not seem to me that any of these match the required functionality.
Also there does not seem to be any information in the zend docs about creating a custom router.
I tried to extend the Literal router and create one of my own by overriding the match()
function and returning the RouteMatch
object if a match was found, but it still gives me a 404 with a notice that thee was no matched route.
The module.config file was ofcourse also edited to add the new router. and added it to the invokables
Can anyone tell me some starters about how to write a custom router or does anyone know any good information about doing this?
Upvotes: 0
Views: 437
Reputation: 2769
First, I don't think you mean directly looking up the directory structure, are you? You should never be doing that. If you've configured your application properly, you won't need it since zf2 handles the autoloading for you.
Anyway, there are a few ways to achieve this.
RouteMatch
object and forward()
to the proper controller from there.Upvotes: 0
Reputation: 4984
Not sure if it is the best way.
You can point all your URLS to one controller e.g. /Controller/RouteController.php. And there you can traverse the url and dispath the appropriate controller:
public function indexAction()
{
$event = $this->getEvent();
$routeMatch = $event->getRouteMatch();
$locator = $this->getServiceLocator();
if ($locator->has('ControllerLoader')) {
$locator = $locator->get('ControllerLoader');
}
$url = parse_url($this->getRequest()->getUri());
$path = str_replace('.json', '', $url['path']);
$path = explode('/', trim($path, '/'));
while (sizeof($path)){
$controllerName = 'Controller\\' .implode('\\', $path);
if ($locator->has($controllerName)) {
return $this->forward()->dispatch($controllerName, $routeMatch->getParams());
}
array_pop($path);
}
//not found
}
Be sure to define your controllers in module config:
array(
'controllers' => array(
'invokables' => array(
'Controller\Foo\Baz' => 'Controller\Foo\BazController',
...
)
),
);
Upvotes: 1