Back to Blog 3 min read

Understanding Facade In Laravel

Today we are going to learn about the term "facade" that we use in Laravel. Since so many days I have wrote this question in my notebook that what it...

Today we are going to learn about the term "facade" that we use in Laravel. Since so many days I have wrote this question in my notebook that what it is actually.

Then I get to know that we can create custom facades in Laravel. So, I have decided that I should write a blog on this topic. we useFacades everyday like DB, Cache etc.

What are the Facade?

In Laravel, a Facade is a design pattern that provides a static interface to the classes that are available in the Laravel service container.

How does Facade works?

This is how facade works in Laravel.

  1. Static Proxy: Facades act as static proxies to underlying classes in Laravel's service container. This means you can access methods on these classes in a static-like manner without needing to instantiate them directly.
  2. Clean Syntax: Facades provide a clean and expressive syntax for accessing Laravel services. For example we can use a facade to access its methods directly.
  3. Global Accessibility: You know Facades are globally accessible, that means you can use them anywhere in your application.
  4. Service Container Integration: Under the hood, facades interact with Laravel's service container to resolve the actual instances of the classes they represent.

I hope you have got some understanding now. What facade do in Laravel. Now we are going to dive into practical way of how to create a custom Facade and how to use them in our application.

Creating A Custom Facade In Laravel

Let's create a custom facade in Laravel in the context of an e-commerce website focusing on shipping services and how a custom facade can be beneficial.

Creating the ShippingService Class

The backbone of our shipping solution is the ShippingService class, residing in app/Services/ShippingService.php. This class contains methods for calculating shipping costs, validating addresses, and handling other shipping-related tasks.

namespace App\Services;

class ShippingService
{
    public function calculateShipping($order)
    {
        // Logic to calculate shipping costs
    }

    public function validateAddress($address)
    {
        // Logic to validate shipping address
    }

    // Other shipping-related methods
}

Registering the Custom Facade

To make the ShippingService accessible via a facade, we create a custom facade class ShippingFacade in app/Facades/ShippingFacade.php.

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class ShippingFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'shipping';
    }
}

Binding with the Service Container

We bind the ShippingService to Laravel's service container in a custom service provider (CustomFacadeServiceProvider) to enable dependency injection and resolution.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\ShippingService;

class CustomFacadeServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('shipping', function ($app) {
            return new ShippingService();
        });
    }
}

Usage in Controllers

With the facade and service provider in place, we can use the Shipping facade in our controllers to perform shipping operations seamlessly.

use Shipping;

public function checkout(Request $request)
{
    if (!Shipping::validateAddress($request->input('shipping_address'))) {
        // Handle invalid address
    }

    $shippingCost = Shipping::calculateShipping($order);

    // Process the order with shipping details
}

Benefits and Conclusion

Implementing a custom facade for shipping services in Laravel offers several benefits. It abstracts complex shipping logic, promotes code organization, and enhances code readability. By encapsulating shipping functionalities behind a facade, developers can focus on building robust e-commerce solutions without worrying about intricate shipping operations.

I think, now you have got the pretty much idea of facade, and how we can create a readable code by using facades in Laravel (sorry custom facades in Laravel).