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!
2 comments