Codementor Events

Beginners guide to facades in laravel

Published Mar 02, 2020
Beginners guide to facades in laravel

In general terms, a Facade (pronounced as  /fəˈsɑːd/) is the exterior and front facing side of a building or any thing. Importance of facades are they are easy to notice and more prominent, similarly there is a concept of facades in laravel too. No, we are not developing a building through laravel rather we are going to manage our code readability and build easy to remember syntax of functions and classes through it.

As you know, there are two types of functions in any programming language so do in PHP, which are non static functions and static functions.

What do we mean by non static functions ?

Let’s take an example of a class vehicle in PHP,

<?php

class vehicle{
    public function wheels(){
        echo "It has wheels";
    }
}

$bike = new vehicle();
$bike->wheels(); //outputs: It has wheels

What we have done here is we are accessing vehicle class’s method wheels() by instantiating vehicle class. Technically, function wheels() is dependent on the instance of class vehicle, so here wheels() is the non static function or just a normal function.

What are static functions, then ?

Here is the catch, static functions, by definition, can not and do not depend on the instance of its class and are declared with the static keyword. As simple as that ?, not yet because they are accessed by :: (double colon). Let’s look at the example below

<?php

class vehicle{
    public static function wheels(){
        echo "It has wheels";
    }
}

Same output as non static function but you have written less code as compared to non static function and easy to remember syntax too, right ?

Obviously, my whole purpose to differentiate non static and static function over here is to give an idea about facades.

What are facades in Laravel ?

According to Laravel’s official documentation, facades are the mechanism of abstraction and encapsulation of the source code in laravel. A Laravel facade is a class which provides a static-like interface to services inside the service container. They serve as a proxy for accessing the underlying implementation of the laravel’s services. For instance write below code in web.php file

//using redis cache
Route::get('/cache', function () {
    cache()->put('hello','world', 600);
    dd(cache()->get('hello'));
});

Output:  world

Above example is using non static way to call cache’s method now let’s see how we do using cache facade.

use Illuminate\Support\Facades\Cache;
//using redis cache
Route::get('/cache', function () {
    Cache::put('hello','world', 600);
    dd(Cache::get('hello'));
});

Don’t you think the above example is more elegant and have easy to remember syntax, right ? That’s the beauty of facades.

Why do we use facades ?

Facades provides many benefits as we discussed that syntax is very clean and memorable, it prevents the pain of creating instance of classes and more importantly all the dependencies are resolved and injected by service container itself. It is more like plug and play thing. Therefore learning and using facades in laravel is best thing to do first.

How do I create a facade class and use in my application ?

Since laravel largely uses facades rather every non static function has its equivalent facade available in service container, we must also follow the same way in our custom application.

All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace. Let’s make a mini project.

Objective of this example

Our objective is to access hello() method of MyClass as static function i.e using Facade.

Step 1. Create a folder with the name “Facades” in app directory

Step 2. Create 2 Files in Facades directory

<?php
namespace App\Facades;

class MyClass{
    public function hello(){
        return 'Yes...It`s working';
    }
}

We created a simple class MyClass with function hello() which returns Yes…It`s working.

<?php
namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class MyFacade extends Facade{
    protected static function getFacadeAccessor()
    {
        return 'my_facade';
    }
}

Next we created a facade class MyFacade which extends Facades base class. Inside MyFacade class we overriden getFacadeAccessor() from base class and this method returns a string, lets call it as alias name for MyClass class.

Step 3. Add the code in web.php

app()->bind('my_facade',function (){
    return new \App\Facades\MyClass();
});

use App\Facades\MyFacade;

dd(MyFacade::hello());

Finally in web.php we binded alias name my_facade with MyClass i.e whenever my_facade is invoked it laravel’s request pointer points to MyClass, indirectly making instance of the class. Lastly we used MyFacade and dump-n-died MyClass’s hello() method using MyFacade.

Quite simple, right ? Hehe.. it happens, but this way is more convenient when you are handling a quiet large project.

Conclusion

One more thing, I am binding the alias name in web.php because this file is already included in service container so when working with controllers you need to make a service provider to inject this facade into service container as we can not bind elements in controllers except service providers or web.php.

Ebooks available now

You can download this article’s PDF eBooks for offline reading from below:

Discover and read more posts from Decode Web
get started
post commentsBe the first to share your opinion
Show more replies