Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the point of using Facade with IoC in Laravel

I don't understand the point of Facade if you are going to inject your class into a controller as part of IoC.

Say I have a custom facade called PostHelper. I have the following 2 functions:

class PostHelper
{
    public function __construct() {} 

    public function all() {}

    public function get($id) {} 
}

To use this helper, with and without facades you would (say in your controller)

// Without Facade
$helper = new PostHelper();
return $helper->all();

// With Facade
return PostHelper::all();

But, this is bad practice since I cannot mock the PostHelper when testing it. Instead, I would pass it to the constructor of my controller:

class HomeController extends BaseController
{
    private $PostHelper;

    public function __construct(PostHelper $helper)
    {
        $this->PostHelper = $helper;
    }

    public function index()
    {
        return $this->PostHelper->all();
    } 
}

In the constructor, I could have just used $this->PostHelper = new $helper() if I had not created a Facade. Either way, I am never using the static feel of a Facade when using DI.

So what is the point of using a Facade?

like image 239
Kousha Avatar asked Nov 09 '22 22:11

Kousha


1 Answers

To quote the documentation:

Facades provide a "static" interface to classes that are available in the application's IoC container. Laravel ships with many facades, and you have probably been using them without even knowing it! Laravel "facades" serve as "static proxies" to underlying classes in the IoC container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

It's just another way of using outside dependencies without needing to understand dependency injection, how to register and/or fetch items using the IoC container, etc. They are a convenience, particularly for inexperienced developers or those new to Laravel.

If you are going to inject your dependencies (which you should), you don't need facades.

You can actually mock facades, but I would still practice normal dependency injection.

like image 85
Aken Roberts Avatar answered Nov 15 '22 11:11

Aken Roberts