Controller as a Service


#1

Hi guys,

Actually, I’m defining routing in this way;

$app->get('/logout', 'App\\Controller\\IndexController:logoutAction')->setName('logout');

Recently, I see that other people to do this instead:

$app->get('/logout', IndexController::class . ':logoutAction')->setName('logout');
and
$container[IndexController::class] = function($c){ return new \App\Controller\IndexController($c); }

They say that the second way is much more faster, because, for example, you can inject not necessary the hole service Container instance but, for example, only the service you need for your controller.

What do you think about this?

Is passing service container really less faster than injecting other services that you could not use in controller??

thanks


#2

@gianluca977 I’m not sure whether or not the performance is better to not pass in the whole container but I’ve been a fan of just injecting exactly what’s needed for the purpose as often as possible.

From the Slim Docs:

Using an invokable class
You do not have to specificy a method in your route callable and can just set it to be an invokable class.

Heres a common pattern I’ve been using:

$c = $app->getContainer();

$c['logoutService'] = function() {
	return new \App\Service\Logout;
};

$c['Logout'] = function($c) {
	return new \App\Controller\Logout($c->logoutService);
};

$app->get('/logout','Logout');

// -------------------------------------

class LogoutController {
	
	public function __construct($logoutService) {
		$this->logoutService = $logoutService;
	}

	public function __invoke($request,$response) {
		$this->logoutService->logout();
		return $response->withRedirect('/login');
	}
}