Is it better to use facades or dependency injection?

By @ralphjsmit · 2021-11-09 09:12

Is it better to use facades or dependency injection?

  • By @samuel · 2021-11-09 13:49

    I almost never use DI. The only exception is packages, in specific classes that are bound to the service container (for instance here although looking at that now it ideally wouldn't inject Application itself).

    One of the main arguments for DI was that it lets you change implementation by binding a class that extends the parent into the service container, like:

    class MyDatabaseManager extends DatabaseManager
    {
        // ...
    }
    
    app()->bind(DatabaseManager::class, MyDatabaseManager::class);
    

    However, Laravel's facades and helpers forward the calls to the service container anyway. So the behavior is identical, and you don't lose any features by using facades or helpers (I personally prefer helpers over facades).

    Then the only remaining benefit (of the ones that are commonly mentioned) is that the class lists its dependencies. I can see the logic behind that, but don't really care about that in general.

    • By @ralphjsmit · 2021-11-09 14:36

      Yes, so this is a highly developer-specific thing. I was asking because I got the idea that DI was widely seen as best practice, but that's then not the case :)