Skip to content

Custom Facade in Laravel?

Last updated on February 17, 2018

In Laravel world, a facade is a class that provides access to an object from the container. Laravel “facades” serve as “static proxies” to underlying classes in the service container, providing the benefit of expressive syntax while maintaining more testability and flexibility than traditional static methods.

When you make a call to a Facade, the Facade resolves the underlying class out of the Laravel IoC container and calls the intended method on the instance.

Below are the steps to create a facade on laravel 5.2

Create a custom class

1. Go to the app folder and create a folder, call it Classes app/Classes. Create a class inside the Classes folder, call it app/Classes/Xtrf.php.


Custom Facade in Laravel 5.2?

Create a facade class

Lets create a directory called "Facades" and inside it create a class called XTRFFacade.php.


Here we are extending the base Illuminate\Support\Facades\Facade class, we only need to define one single method called getFacadeAccessor(). The getFacadeAccessor method's job to resolve the defined class from the container.

Create a provider

Create a service provide class using artisan tool. Lets open terminal in your project folder and issue the below command. Which will create a new file called XTRFProvider.php under app/providers directory.

php artisan make:provider XTRFProvider

Open our XTRF provider, it has boot and register functions, lets inject our XTRF calls object into container using register method.

app->bind('xtrf', function () {
            return new \App\Classes\Xtrf;
        });
    }
}

Register ServiceProvider

Register that ServiceProvider to Config\app.php as providers

         /*
         * Application Service Providers...
         */
        App\Providers\XTRFProvider::class,

Add facade class reference to aliases

Register that ServiceProvider to Config\app.php as providers

         /*
         * Application Service Providers...
         */
        'Xtrf' =>  App\Classes\Facades\XTRFFacade::class,

Testing

On App\Http\routes.php create single route

Route::get('/', function(){
    Xtrf::getProjects();
});

Then point your browser to app URL, you will see "Project list" text on the screen.

0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments