While looking through some source code on Github, I noticed some packages use the app container itself to access the IOC, not Facades. Why would you use something like this...
$app = app();
$user = $app['db']->connection()->table('users')->where('name', '=', 'Foo')->first();
...instead of this?
$user = User::where('name', '=', 'Foo')->first();
Motive 1
Some packages need to.
Usually you are going to see ServiceProviders using it this way:
Or inside a closure binding:
Because
$app
is a property ofIlluminate\Support\ServiceProvider
and ServiceProviders are the guys who boot up services that will be used by Facades in your app.So, first Laravel will instantiate and boot all ServiceProviders who provides the IoC binded service, for instance:
And after that particular call you have access to the Facade:
Before that, what you get is an error telling you that there is no 'db' binded.
And I have to stress that you will mostly see that being used on ServiceProviders that way, because the closure provides the
$app
variable to use it this way:Of course anyone can get the IoC binding for app and set it to an
$app
var...Motive 2
Some others might overuse that to not break their packages easily. Relying on an Alias to make your package work is dangerous, because if the user changes that alias the package could break. That might be a user problem, but it would create some problems to them too, like issues on Github.