Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 class loading and facades

I want to know how Laravel does class loading via Facades.

I came across this answer that said that the DB alias/facade class loaded the code

here /vendor/laravel/framework/src/Illuminate/Database/Connection.php

I tried following the advice given in the answer and following what the code does from index.php but could not understand how the DB Facade loaded the Connection class.

I also got confused some more, because the answer had said that the Connection class is loaded, but that class has no connection method. Yet the documentation says and I have been able to use the connection method like,

DB::connection('my-connection-name'); here's the link to the docs for this

I want to know where this is all mapped and how does the loading happen. I am guessing that composer has automated the mapping, but where is it actually happening when my application boots?

like image 353
kapad Avatar asked Dec 09 '22 17:12

kapad


1 Answers

When you use the static DB call Laravel use the mechanism provided by the Facade class in Illuminate\Support\Facade. The magic method __callStatic is called and retrieved the "original" class which is provided by the DB facade (here db).

The line 54 in Facade.php show that it use the $app variable (which is static and provided in Illuminate\Foundation start.php file) to get the object registered as DB in the App container.

return static::$resolvedInstance[$name] = static::$app[$name];

$app['db'] is registered in the database service provider.

Ah, and you are able to use DB and not Illuminate\Support\Facades\DB because an alias is created in app config file.

I hope this will help you :)

like image 72
SelrahcD Avatar answered Dec 11 '22 09:12

SelrahcD