Route Callable Prefix


#1

Hello,

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.


#2

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.


#3

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?


#4

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.


#5

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

<?php

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.