How to create a Laravel facade

Create a Laravel facade: step-by-step guide with example.

A Laravel Facade is a class that provides a static-like interface to classes that are available in the application's service container. You can think of it as a way of providing a "shortcut" to accessing other classes in your application. In this tutorial, we'll look at how to create and use a custom Laravel Facade.

Creating a Facade

First, let's create a new class for our Facade. This class should be placed in the AppFacades directory. For this example, we'll create a Facade called MyFacade:

<?php

namespace AppFacades;

use IlluminateSupportFacadesFacade;

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

The getFacadeAccessor method is what tells Laravel which service to pull out of the service container. In this case, we'll use a service called MyFacade, which we'll create in the next step.

Creating the Service

Now that we've created our Facade, we need to create the service that it will be accessing. In this case, we'll create a new class called MyService and place it in the AppServices directory.

This class will contain the logic that our Facade will be accessing. For this example, we'll just create a simple method that returns a string:

<?php

namespace AppServices;

class MyService
{
    public function getMessage()
    {
        return 'Hello from MyService!';
    }
}

Binding the Service to the Container

Now that we have our Facade and Service, we need to bind the Service to the application's service container. We can do this by adding the following line to the register method of the AppServiceProvider class:

$this->app->singleton('MyFacade', function () {
    return new AppServicesMyService;
});

This will bind the MyService class to the MyFacade service in the application's service container.

Using the Facade

Now that we have our Facade and Service set up, we can use the Facade in our application. We can do this simply by calling the MyFacade Facade class, followed by the method that we want to access:

$message = MyFacade::getMessage();

// 'Hello from MyService!'

And that's it! We've now created a custom Facade that we can use in our application.

Answers (0)