Home > Enterprise >  How Laravel creates object of any class
How Laravel creates object of any class

Time:10-14

I am new to laravel framework and I am not clear about laravel object creation. How laravel creates object of classes?

Like for Eg. I have controller called class MyTestController and it has method defined called MyMethod()

This is route for this controller, Route::get('Test',[MyTestController::class,'MyMethod']);

when I hit -- http://localhost:81/laravel_project/Test,

MyMethod() gets called. I have not created MyTestController class object with new keyword then how it's method is called?

Does framework creates object behind scene.

CodePudding user response:

Try this

Route::get('Test', function(){
$object = new MyTestController();
 var_dump($object);      
 });

CodePudding user response:

In another words, yes, Laravel creates the object behind the scenes, however, it is not recommended/rare for you to create stated objects (such as Controllers, Models, etc.) in Laravel Framework based on my experience because that is what frameworks do, they make it simplier for you. For example, take Models, by adding where($id)->first() code after the Models' name (final code is Model::where($id)->first()), Laravel will create for you the Model's object based on the query's result when the method first() is called. There is a lot of methods that has the same behavior as first(), get() is one of them too, the difference is first() will give you just 1 object, while get() will give you an array that wraps the result even though it only matches 1.

In your case, which is Controllers, basically hassan and apokryfos has answered it for you.

  • Related