External callback function for routes


I’m pretty sure this is just my lack of understanding of how to use PHP callables properly, but I hope you guys can help me anyway:
I already have a lot of routes that work just fine:
$app->get(’/test’, function (Request $request, Response $response) {
lots of stuff});

However, the function body of many routes becomes very unwieldy, so I’d like to refactor everything, so the actual code is inside specific functions, and only a very short route declaration is left over that I can manage in a more central place. This gives me a bunch of benefits (easier to read, swagger&phpdoc for functions, useful function names in outline instead of __anonymous etc.).
So I simply moved the function on its own, and gave it a name:
function get_test( Request $request, Response $response) {
lots of stuff});
and then defined the route as
$app->get('/test', get_test($request, $response));

Which doesn’t work, giving me a “$request is undefined”) error message. What does work:
$app->get('/test', function($request, $response) {return get_test($request, $response);});
Which however feels unnecessarily bulky.

Surely there’s an easy and simple way to do what I am looking for?


I believe what you are looking for is the Container Resolution section of the docs. Instead of using a function you can use a Controller class. You can see an example of this in the slim-bookshelf example app, routes.php.


That is exactly the kind of easy solution I was looking for :slight_smile: . In my case, it would be as simple as:
$app->get('/test', 'get_test');

I failed because the correct solution is even shorter&smarter than I expected. I love Slim more and more <3 .