Route Callable Prefix



Probably been asked before, but I’m fairly new to Slim (and love it btw).

Coming off Laravel, they made it easier to use a Class::method without calling the full namespace (e.g App\Http\Controllers\Home\HomeController:class)

Is there anyway to modify/add something in Slim so that I can use shorter namespaces in routes?

For example, instead of doing:

$app->get('/page', App\Http\Controllers\Home\HomeController:class);

I’d like to do:

$app->get('/page', Home\HomeController:class);

but, the full namespace would still be like the first example, so the app knows to prefix “App\Http\Controllers” for every route that uses the class path.

I’ve read through the Router documentation, but I can’t seem to see if it’s possible.


Yes-- If you define your Controller in the container, Slim will find it there. See the Container Resolution (Router Object) section of the docs for details.


Doesn’t that require me to tell Slim to look in my App\Http\Controllers folder if I’m defining “\HomeController:class” in a route?


If you have something named HomeController in your container, that instantiates App\Http\Controllers\HomeController, you can then just use the shorthand HomeController in your routes.

Or, if you use PHP-DI instead of the provided Pimple, I believe that does support “wildcard” entries which could likely be used to do that without defining it in the container. PHP-DI also gives you autowiring via reflection.


AFAIK this is a PHP feature, nothing to do with Slim. You can import specific classes or full namespaces and use the shorthand notation:


use Slim\App;  // Class import
use App\Http\Controllers\Home; // Namespace import

$app = new App();  // rather than new \Slim\App();

$app->get('/page', Home\HomeController::class);

PD mind that you need to write two colons before the class keyword, not one.