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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With