Zend framework 3 routers in separate file (not in config array tree)

zend-router
zend-mvc
#1

I am using this tutorial https://docs.zendframework.com/tutorials/getting-started/overview/ for creating album module. It works for me.

Inside project there is /module/Album/config/module.config.php file which contains routes. Routers are located inside an array tree. As my previous experience shows I can have in the future dozens of routes per a project (even per a module).

On this documentation page https://docs.zendframework.com/zend-router/routing/ I found another way to add routers to the module.

// One at a time:
$route = Literal::factory([
    'route' => '/foo',
    'defaults' => [
        'controller' => 'foo-index',
        'action'     => 'index',
    ],
]);
$router->addRoute('foo', $route);

Such a way is preferred for me than storing routes in a very deep config array tree.

So, my question is: where I can put php routers code outside a config tree as I have mentioned earlier? Where in the module should be such a routers-file located at?

#2

This is not precisely an answer to your question, but a different approach. I do this in module.config.php when config arrays get too huge:

 return [

    'router' =>  include __DIR__.'/routes.php'
    ,
    'controllers' => [
           /* etc */
        
    'view_manager' => [
        'template_map' => include(__DIR__.'/template_map.php'),
        'template_path_stack' => [
            __DIR__.'/../view',
        ],
    ],
    // etc

and it seems to work just fine.

1 Like
#3

I also saw another proposition to keep routes in separate files and then merge them together.

#4

You can do in Module::onBootstrap() like the following:

<?php 

namespace Application;

use Zend\Mvc\MvcEvent;
use Zend\Router\Http\Literal;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $services = $e->getApplication()->getServiceManager();
        $router   = $services->get('Router');

        $route = Literal::factory([
            'route' => '/foo',
            'defaults' => [
                'controller' => Controller\IndexController::class,
                'action'     => 'index',
            ],
        ]);
        $router->addRoute('foo', $route);    
    }

    public function getConfig() { /* ... */ }
}
1 Like
#5

It seems, I was searching exactly for this solution.