Search code examples
phplaravelsyntaxroutescontroller

What is the reason behind controllers is declared as a string in routes for Laravel?


I am new to Laravel and something I have not understood is why the routes can be declared as a string. I think there is a good reason behind it just I don´t get it. Could someone explain it?

The two ways I found to declare a route using a controller in Laravel.

First: Route::get('hello', 'UserController@index');

Second: Route::get('hello1', [UserController::class, 'index']);

However why should it be possible to make the function static and call it like this instead (I tried but did not work):

Route::get('hello2', UserController::index());

I think the last one should make it easier to autocomplete in IDE (the second works in my IDE, but still feels over complicated). So what is the reason for the string syntax? Once I again I am new to Laravel so understad its something I miss.


Solution

  • The controller cant just call the method because it will make things more difficult to change later. When the controller gets to connected to the methods details, it will be tough to keep the code in good shape.

    Better the controller should pass the methods reference as a parameter. This way the controller can use the method without getting tangled up in its specifics. Its a better way because it makes the code more flexible and easier to work on.

    This is called "dependency injection" and its common to do in frameowrks. Its better to inject dependencies into a component than to have it create them directly. That way the component will be easier to test and maintain.

    Passing a methods reference as a parameter is better than calling it directly. It helps to keep the controller from getting tied to the methods details. Making the code more adaptable and maintainable.