Search code examples
phplaravelperformancesecuritylaravel-routing

Laravel call app action VS call class object directly


When we can call controller method directly by create object of class like this

Route::get( 'url/{parameters}', function() {
  $controller = new ClassController;
  return $controller->classMethod($parameters);
});

why we should use app and call action?

Route::get( 'url/{parameters}', function() {
  $controller = app()->make('ClassController');
  return $controller->callAction('classMethod', $parameters);
});

Is there any advantage for call action or security disclosure/breach for call class object directly?


Solution

  • The difference between new ClassController and app()->make('ClassController') is that when you use app()->make you are making use of Laravel's service container to "resolve" an instance of ClassController.

    The service container makes it more convenient to resolve dependencies. For example if your ClassController's constructor had dependencies such as a ClassRepository when you use the repository design pattern, it can be resolved by the container instead of you having to pass it a new instance, e.g. new ClassController(new ClassRepository(new User)).

    It also makes your code more easily testable. You would be able to use a mock instance of either your controller or your controller's dependencies when you want to test your code.

    However, using new ClassController instead of app()->make('ClassController') doesn't make your code more or less insecure.

    At this stage there seems to be basically no difference between using ->classMethod($parameters) and ->callAction('classMethod', $parameters). From the source it seems that callAction simply uses call_user_func_array to call the method you pass it using the parameters. I suspect it might just be left over in the code for compatibility reasons because callAction used to do more in older versions of Laravel.

    It does still get used by Laravel's routing mechanism so you might want to use it in case callAction gets updated in the future. However, at this stage there's no difference between the two other than that with callAction you will be able to call private and protected functions on the controller.

    All-in-all there are no security-related reasons you need to use the app()->make and callAction, but for testability and convenience reasons (in the case of app()->make) and for compatibility reasons (in the case of callAction) you might want to use them.