Extend Routes By files?

hi , i just try my first slim project.
i have many Routes (a lot of database requests)
i want to split the index -> to more then one file -> each file to his own table.
4 example ->
to do …
in index:
require ‘…/src/contacts.php’;
require ‘…/src/container.php’;
require ‘…/src/ContainersTypes.php’;

$app->run();

and in each file do
$app->get(… )

what is the best way to do this?

If I’m understanding you correctly, that should work fine the way you have described.

2 Likes

You can do it in two (or more) way.

  1. Split the routes in different files and require it before the run method.
  2. Build an object that will load all your routes and will register them to the app.

The first one is the faster, so it’s ok also require all the files :smiley:

For my apps I parse the url first before involving Slim routes to determine which component I need to load.

My app component structure:

app/components
  /contacts
	/controllers
	/models
	containers.php
	index.php

 /users
	/controllers
	/models
	containers.php
	index.php

The base route in the url determines which component to load:

www.myapp.com/contacts
www.myapp.com/users

The index.php file in the component dir (app/components/contacts/index.php) requires the containers and sets the routes.

I use a switch statement in my router for some routes that might not follow this guideline.

// app/config/router.php

$_url = parse_url($_SERVER['REQUEST_URI']);
$_routes = explode('/',$_url['path']);
$_baseRoute = $_routes[1];
$_componentFile = 'app/components/' . $_baseRoute . '/index.php';';

switch ($_baseRoute) {
	case 'someweirdroute':
		require 'app/components/myOneOffComponent/index.php';
		break;

	default:
		if (!file_exists($_componentFile)) {
		  die('Invalid Request');
	    }
	    require $_componentFile;
		break;
}

Here’s how I set it up in public/index.php:

chdir(dirname(__DIR__));

require_once 'vendor/autoload.php';

$app = new Slim\App;

// custom router
require 'app/config/router.php';

$app->run();

Hope this helps