In this post, I will cover what is facades in Laravel, how to create your own custom facades and use them in Laravel applications.
Probably, facades are one of the discussed topics in the laravel community.
According to Dictionary.com
The word ‘facade’ refers to a “superficial appearance or illusion of something.” In architecture, the term refers to the front of a building. Any side of a building facing a public way or space and finished accordingly
In general terms, a facade is the front face or public face of a building. Facade gives a nice outer look of the building by hiding the inner complex structure and makes it easily noticeable.
Similarly, there is a concept of facades in Laravel too. Which is used to wrap a complex library to provide a simpler and more readable interface. It makes syntax simple and easily memorable.
According to Laravel documentation,
“Facades provide a “static” interface to classes that are available in the application’s service container.”
In simple words,
A facade in Laravel is a wrapper around a
non-static
function that turns it into astatic
function.
In Laravel, we have seen many functions that are called statically. These all are examples of built facades.
DB::get('users')->all();
Route::get('/', function () { });
Config::get())
You can find more built facades in Laravel Documentation
Benefit of Using Laravel Facades
Laravel facades serve as static proxies
to underlying classes in the service container.
It provides easy and expressive syntax which is more
maintainable, testable and flexible than traditional static methods.
Static vs Non-static in PHP
In definition, we touched the static
function and non-static
function.
Let’s understand what static and non-static functions are in PHP.
What is a static function in PHP?
Static functions are those functions which do not depend on the instance of the class. In simple words, static functions do not require an instance of the class to execute.
Static methods use double colons (::)
while accessing properties or methods of a class.
Example Code: