Northys
Northys

Reputation: 1313

How can I split router lists into modules?

I have this router list:

$router[] = $adminRouter = new RouteList('Admin');
$adminRouter[] = new Route('admin/<presenter>/<action>', 'Dashboard:default');

$router[] = $frontRouter = new RouteList('Front');
$frontRouter[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default');

But it would be better to separate those two router lists into module folders. In the future I will probably create more modules with different router lists. How can I separate it and after how can I register it?

Upvotes: 1

Views: 574

Answers (1)

Josef Nevoral
Josef Nevoral

Reputation: 116

Use RouteFactory

In config.neon

services:
  routeFactory.Front: FrontModule\RouteFactory
  routeFactory.Admin: AdminModule\RouteFactory
  route:
    class: \RouteFactory
    setup: 
      - addRouteFactory(@routeFactory.Front)
      - addRouteFactory(@routeFactory.Admin)

Class RouteFactory:

class RouteFactory
{
  /** @var array */
  private $routerFactories = array();


  public function addRouteFactory(IRouteFactory $routeFactory)
  {
    $this->routeFactories[] = $routeFactory;
  }

  public function createRouter()
  {
    $router = new RouteList();
    foreach ($this->routeFactories as $routeFactory) {
      $router[] = $routeFactory->createRouter();
    }

    return $router;
  }
}

Interface IRouteFactory:

interface IRouteFactory
{
  public function createRouter();
}

Module route factories

namespace FrontModule;

class RouteFactory implements \IRouteFactory
{
  public function createRouter()
  {
    $router = new RouteList('Front');
    // your routes

   return $router;
  }
}

Upvotes: 3

Related Questions