Routing cache seems useless in Slim 4

Hi!

First of all, I’m a newbie in the Slim framework.

Everything is going fine except the router cache. I thought if I enabled cache using:

$app->getRouteCollector()->setCacheFile(...)

I can now disable all my manual routing definitions and use a cache file instead. But it seems I still need routing definitions alongside the cache file.

That’s how any cache should work otherwise - why the hell do I need this cache file if I’m anyway should manually do the same, but now with the cache file present? What is the benefit of using this cache file then?

Is there anything I’m missing, or is it expected behavior?

I understand the callable can not be serialized, but at least PHP-DI resolved this issue by code generation, like:

protected function get3()
{
    $object = new \Service();
    return $object;
}

or

protected function get1()
    {
        return $this->resolveFactory(static function (\Psr\Container\ContainerInterface $container): \Slim\App {
        $app = \Slim\Factory\AppFactory::createFromContainer($container);

        return $app;
    }, 'Slim\\App');
}

Why can’t routing be cached in that way?

Hi @sanich

Under the hood Slim uses FastRoute as Router and this routing cache file is designed to speed up the performance of your application by caching the route computation results.

When the router cache file is enabled, Slim uses the cachedDispatcher instead of simpleDispatcher to cache the generated routing data and construct the dispatcher from the cached information.

Example cache file:

<?php return array (
  0 => 
  array (
    'GET' => 
    array (
      '/' => 'route0',
      '/users' => 'route1',
      '/customers' => 'route3',
    ),
    'POST' => 
    array (
      '/customers' => 'route2',
    ),
  ),
  1 => 
  array (
  ),
);

Even with the cache enabled, you still need to define your routes as usual. The cache doesn’t replace the need for defining routes; it simply optimizes the lookup process. The route definitions are essential for Slim to understand how to handle different URLs.

The primary benefit is performance optimization, especially for applications with a large number of routes.

I never had any performance gain in practice, though.

Hi, @odan. Thanks for your reply.

The cache doesn’t replace the need for defining routes; it simply optimizes the lookup process.

Yeah, I have spent a couple of hours debugging, so I saw how this works. Anyway, I was hoping there was something I was missing, and it’s only my fault not to do the trick.

There is no information about it on the internet, and I don’t trust AI tools (yet, at least), so I’ve decided to ask a question there.

I never had any performance gain in practice, though.

Me neither. It could be a micro-optimization rather than something game-changing.

Anyway, I’d like to read this fact from the docs and not spend time debugging the framework because it’s not working as expected to work.