MarcoMdMj's avatar

L5: Facades or dependency injection?

Good day.

I'm a bit confused about dependency injections. According to the official docs, it is some cleaver way of "include" all dependencies in a controller or method.

I wonder, what is the real difference between this:

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class UserController extends Controller {
    public function store(Request $request)
    {
        $name = $request->input('name');
    }
}

and this?

<?php namespace App\Http\Controllers;

use Request; // Facade of Illuminate\Http\Request
use Illuminate\Routing\Controller;

class UserController extends Controller {
    public function store()
    {
        $name = Request::input('name');
    }
}

Does any of them performs better or faster? Or do they do completely different things?

Thanks.

0 likes
4 replies
bestmomo's avatar

Many developpers dont like facades because dependency injection gives a clearer control on code. Your 2 versions are good but the first one would be better practice.

1 like
DMA's avatar
DMA
Best Answer
Level 2

Dependency injection allows you to decouple your code from the specific implementation of whatever resource it is you're working with, so in theory you could swap out a MySQL database class for a totally different type of database as long as they both adhere to the same contract.

Also, is your controller really responsible for creating instances of various objects? I'd say no.

It also has a lot of other useful benefits, specifically linking with Laravel's IoC containtainer. Namely, not having to manually instantiate the objects you're working with, and their dependencies which can be quite complex and difficult to keep track of.

Those benefits may not apply to your specific application, especially if what you're building is fairly simple, like a blog but it's useful to know what DI and IoC is, so that you can write better code in instances where you can apply it.

Regarding the question of Facades vs DI, the difference in speed is negligible. I personally use the first example as it allows for better testability and is a cleaner way of doing things. But, sometimes it's better to just start with what you know and what works - and then incrementally decide how you can improve your application.

2 likes
cashtivity's avatar

What about dependency injection in Models? How can we achieve the same results?

Please or to participate in this conversation.