Welcome to Abdul Malik Ikhsan's Blog

Programmatically add route in zend-mvc application

Posted in Tutorial PHP, Zend Framework 3 by samsonasik on June 16, 2019

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!