Programmatically add route in zend-mvc application
Yes, we usually setup routing via configuration in our module.config.php in our modules. However, in very specific condition, we may need to programmatically setting it. There is a ‘Router’ service for that, it represent Zend\Router\Http\TreeRouteStack
instance and we can use addRoute()
method against it.
For example, we need to setting it in Module::onBootstrap()
, so we can code like the following:
<?php namespace Application; use Zend\Mvc\MvcEvent; use Zend\Router\Http\Literal; class Module { public function onBootstrap(MvcEvent $e) { // if ( ... condition to be handled programmatically ... ) : $services = $e->getApplication()->getServiceManager(); $router = $services->get('Router'); $route = Literal::factory([ 'route' => '/foo', 'defaults' => [ 'controller' => Controller\FooController::class, 'action' => 'index', ], ]); $router->addRoute('foo', $route); // end if } public function getConfig() { /* ... */ } }
That’s it!
Interesting, but I’m trying to imagine a case where you would want to do this, and what the advantage would be. The route does not persist beyond the lifetime of the request cycle, right?
For example, you have a specific session to allow/not allow to know that specific page exists.