DEV Community

Rohit Urane
Rohit Urane

Posted on

How to Create Custom Facade in laravel?

Image description

In this article, We are studying facades in laravel. A facade is a design pattern that provides a static interface to classes inside the framework's service container. You can access all the features of laravel with facades. It provides the benefit of a terse, expressive syntax while maintaining more testability and flexibility.

Some of the laravel facades

  • Cache: Access the caching system.
  • Config: Access the configuration values.
  • DB: Interact with the database using Laravel's query builder
  • Log: write a log message
  • Mail: Access the Mailing system.
  • File: Perform file operation
  • Route: handle HTTP request
  • Storage: handle file system.
  • Session: Manage session data

Laravel contains many facades to handle the core functionality of laravel. Also, you can create custom facades that allow you to access them more concisely throughout your application.

How to create a custom Facade in Laravel

Create a helper class

Create a "Message" directory inside the App directory and create a php class inside the directory.

<?php
namespace App\Message;

class WelcomeMessage
{

    public function greet()
    {
        return 'Welcome to Our Platform';
    }
}
Enter fullscreen mode Exit fullscreen mode

Register helper class

You can register a helper class in AppServiceProvider Provider.

public function register()
{
    $this->app->bind('greeting', function(){
        return new WelcomeMessage();
    });
}
Enter fullscreen mode Exit fullscreen mode

You can read the article on website

Top comments (1)

Collapse
 
xwero profile image
david duymelinck

I like to use interfaces instead of facades. See my post on how to make app binding less of an manual process.

One thing I discovered recently is that there are real time facades.
This works by prefixing any class with Facades and call the methods statically. It even gets rid of adding it as a parameter of your methods.

It is a bit too much abstraction for my taste, but for people that prefer the facade syntax this is an easy way to go from interfaces to facades.