2

Excuse my ignorance, but how does using a front controller compare in memory usage to using a static router? I'm particularly curious to how this applies in PHP.

Example of front controller (pseudo-code)

// index.php

$path = getRequestedPath();
$class = 'Controller_'.$path;

if (classExists($class)) {
    $ctr = new $class($req, $resp);
    $ctr->execute();
} else {
    $resp->setError(404);
}

// ...

Example of static router (I may be calling this the wrong thing)

// index.php

$router = new Router();

$router->get('/', function($req, $resp){
    // instantiate service classes
    // use service classes
});

$router->get('/products', function($req, $resp){
    // instantiate service classes
    // use service classes
});

$router->get('/product/:productId', function($req, $resp){
    // instantiate service classes
    // use service classes
});

$router->post('/product/:productId', function($req, $resp){
    // instantiate service classes
    // use service classes
});

// ...

Seems like the frameworks of yesterday were all based on the first pattern. Now I'm under the impression that the new trend is to use something similar to the second example, where you list every possible path to your app/api.

Is it just me, or does the second example really allocates memory to lay the entire app in memory, although only a single path is served per request?

tereško
  • 56,151
  • 24
  • 92
  • 147
rodrigo-silveira
  • 10,557
  • 9
  • 55
  • 98

1 Answers1

1

So, lets take for example:

$router->post('/product/:productId', function($req, $resp){
    // function body goes here
});

When you at code like this, you have to understand that it does not mean, that the function body is being executed ever. It is just a definition of an anonymous function.

Basically that means that function(){ ... } in memory will have an equal memory footprint as any normal function. And, while I personally thing, that mixing routing with dispatching, is a bad idea, this does not have any substantial impact on PHPs total memory usage (the difference in a complete app would probably end up being like 1KB).

P.S.: I really like using anonymous functions for initializations of PDO and SOAP stuff (like shown here), because it lets me defer (or, in some requests - avoid) initializing "expensive" objects.

Community
  • 1
  • 1
tereško
  • 56,151
  • 24
  • 92
  • 147