Is it possible to load only required routes?


#1

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 >> https://www.slimframework.com/2011/09/24/how-to-organize-a-large-slim-framework-application.html

How to achieve this?


#2

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.


#3

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;
}
$app->run();

That will make require hundreds router file in every request.

Is there any more eficient way?


#4

How many routes are in each file?


#5

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


#6

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

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

#7

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.


#8

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


#9

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.


#10

Just to give you an idea how it can work.


#11

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


#12

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: