Compare the service container, dependency injection, and facade patterns in Laravel

Laravel

Some of Laravel's power comes from shortcuts to perform complex code operations. Key to using these tricks is understanding the service container, dependency injection, and facades, because these three make it super easy to do more complex object oriented work.

For example, do you really have to instantiate and object, and then call it's method?

$api = new Amazing::class;
$api->goBig();
lang-php

See here? Two lines of code when you maybe only want to use or remember one.

Another good example is something like this:

$api = new Secure();
$api->username = "Joe";
$api->password = "Secret";
$api->callMethod();
lang-php

Now we have four lines of code just to call a method or a fixed entity.

Perhaps you might say reduce it like so:

$api = new Secure($username, $password);
lang-php

Sure, that works, but what about `URL`? Where do we store that, the first parameter? Somewhere else?

Of course, the other classic example is what if instantiating `$api` means we also first needed to instantiate another class? A dependency?

Does that mean we have to do this?

$newClass = new firstInstantiateMe();
$api->useClass($newClass);
lang-php

Dependency injection means you don't have to worry about a class and it's dependencies.

I could not summarise it any better than below. The only thing left to learn then is how to create service providers, because service providers bundles this all up together.

service container vs di vs facade.png 139.26 KB