fideloper / Implementing-Laravel

Companion application to the e-book Implementing Laravel
173 stars 40 forks source link

When to inject dependencies and when to use Facades #4

Closed barthompson closed 10 years ago

barthompson commented 11 years ago

Hi there,

I have bought your book 'Implementing Laravel' and have also read most of your blog at Fideloper.com (including the post 'How to Create a Facade in Laravel 4').

From my reading, I understand the code and syntax of using both dependency injection as well as Facades, however, what I am not clear on is when you should use one or the other??

Could you possibly just outline a few simple guidelines as to when to use one or the other and the advantages/disadvantages of each approach?

In fact, it would be particularly helpful if you could add your post on Facades to the book and include a Facade in the 'Implementing Laravel' app to illustrate this distinction.

Many thanks for all your help to date. Both the Book and your blog are excellent!

fideloper commented 11 years ago

My take on Facades:

With Facades, you end up using a class directly in a model/business logic class. In this way, Facades circumvent the use of dependency injection.

This makes testing and maintainability harder.

  1. Lack of DI in business logic makes you unable to mock the Facade
  2. You have a (somewhat) concrete dependency ( coupling! ) in your business logic which can't easily be "swapped out" at a later time.

Now, technically, a Facade DOES let you swap out what class is used underneath it (That's what you're doing getFacadeAccessor() method in your Facade). So the above points aren't technically true, but they are from a pragmatic standpoint:

  1. Testing: In order to test your code, you then need to bootstrap laravel and it's containers to test your business logic if you mix Facades into your business logic.
  2. Maintainability: Swapping them out also becomes problematic if you are relying on a Facade in one place, but need a different implementation of it in another. You effectively switch the implementation out EVERYWHERE in your application, if you change what class a Facade is using. With DI, you can change implementations at a specific class level, rather than "globally".

Where do I used Facades?

I use them in any Laravel class that is not part of my business logic libraries - Almost purely within Controllers. Sometimes within an Eloquent model (not in a "repository", but just within an Eloquent model itself).