Is it possible to load only required routes?

After a long time of development process, I have hundreds of router files.

I was using glob to load router files. Now I just think that is it possible to only load some router to save memory on every request?

For example, to load login page, i just load router for login only.

The reason i using glob because i have read this article >>

How to achieve this?

Which version of Slim are you running? That article is pretty old and refers to an old version of Slim.

If you have hundreds of route files, do you have hundreds of routes in each file? The first thing that comes to mind is that your route organization might not be correct-- you might be writing many more routes than you need. Unless you have a massive, complex application.

In Slim 3 you can “compile” all of your routes into one router cache file. You can find information on that in the Slim Default Settings section of the docs, see routerCacheFile.

I use slim3.

As far as i know, routerCacheFile is to make the fastroute to not compile the routes in every request.

But the script still make a require for hundreds file.

Currently i have this on index.php

$app = new Slim();
$routes = glob('routes/*.router.php');
foreach($routes as $route) {
  require $route;

That will make require hundreds router file in every request.

Is there any more eficient way?

How many routes are in each file?

Mostly it have arround 6-9 routes in each file.

I have not tested it, but you could try to group the routes like this:

$app->group('/users', function () {
    require 'routes/users.router.php';
1 Like

your solution seems possible, but it will really hard because i have to edit hundreds file.

i will try to make test and benchmarking later.

I use a dynamic routerresolver, so that skips the need of “coding” a route into a routes file.
(and it’s fast enough)

Can you post some examples of your dynamic routes? I’m was thinking of doing this for my next project but your sample code will help me figuring this out.
Thanks in advance.

Just to give you an idea how it can work.

Is it good to use any params? Im affraid this routeresolver will very complicated when app grow to big scale.

It doesn’t grow unless you do a lot of wierd stuff. The trick is, that it just finds out via reflection what to do, and you never ever have to add another route by hand. Call me lazy :wink: