How to Create And Use Laravel Facades?

10 minutes read

Laravel facades provide a simple and convenient way to access classes and services in the Laravel framework. By using facades, you can obtain instances of classes without explicitly initializing them. Facades serve as static proxies to underlying classes which means that you can call methods on them as if they are static methods, even though the underlying class may not actually be static.


To create a new facade in Laravel, you need to follow these steps:

  1. Create a new PHP class that will act as the facade. This class should extend the Illuminate\Support\Facades\Facade base class.
  2. In this new facade class, create a protected static method called getFacadeAccessor(). This method should return a string that corresponds to the name or identifier of the service or object you want to access via the facade.
  3. Optionally, you can override the getFacadeAccessor() method to customize the way the facade resolves its underlying object. This is useful when you need to define your own logic to resolve the dependency.
  4. In your facade class, you can define any additional methods that you want to make available as static methods on the facade. These methods will be executed on the underlying object when called.


Once you have created the facade class, you can start using it in your application by referencing the class name statically. For example, if your facade class is named MyFacade, you can use it like this: MyFacade::someMethod(). Laravel will resolve the facade's underlying object using the getFacadeAccessor() method and then execute the desired method on that object.


Using Laravel facades can simplify your code and make it more readable. It allows you to access important services and components without having to initialize or inject them explicitly throughout your codebase. Laravel provides several built-in facades, such as DB to access the database, Auth for authentication, and Cache for caching, among others.


Remember to import the facade class at the top of your files or you can use the fully qualified names when calling methods on facades. For example: Illuminate\Support\Facades\DB::table('users')->get().

Best Laravel Frameworks Books to Read in 2024

1
Laravel: Up and Running: A Framework for Building Modern PHP Apps

Rating is 5 out of 5

Laravel: Up and Running: A Framework for Building Modern PHP Apps

2
Beginning Laravel: Build Websites with Laravel 5.8

Rating is 4.9 out of 5

Beginning Laravel: Build Websites with Laravel 5.8

3
Laravel: Up & Running: A Framework for Building Modern PHP Apps

Rating is 4.8 out of 5

Laravel: Up & Running: A Framework for Building Modern PHP Apps

4
Laravel: Up & Running

Rating is 4.7 out of 5

Laravel: Up & Running

5
Practical Laravel: Develop clean MVC web applications

Rating is 4.6 out of 5

Practical Laravel: Develop clean MVC web applications

6
Laravel - Un framework efficace pour développer vos applications PHP

Rating is 4.5 out of 5

Laravel - Un framework efficace pour développer vos applications PHP


How to define the contract for a Laravel facade?

To define the contract for a Laravel facade, you need to create an interface that specifies the methods and functionality that the facade will provide. Follow these steps to define the contract for a Laravel facade:

  1. Create a new interface file: Start by creating a new file in the 'app/Contracts' directory or any other appropriate location. Name the file with the name of the facade you want to create, followed by 'Interface.php' (e.g., MyFacadeInterface.php).
  2. Define the interface: Inside the interface file, define the methods that the facade should implement. You can define any number of methods in the interface, depending on the functionality you want to expose through the facade. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

namespace App\Contracts;

interface MyFacadeInterface
{
    public function method1();

    public function method2($param1, $param2);
    
    // Add more methods as needed
}


  1. Create the facade class: Now, create a new class file for the facade in the 'app/Facades' directory or any other appropriate location. Name the file with the name of the facade (e.g., MyFacade.php).
  2. Use the facade namespace: Inside the facade class file, add the appropriate namespace for the facade class. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

namespace App\Facades;

// Import the facade contract interface
use Illuminate\Support\Facades\Facade;
use App\Contracts\MyFacadeInterface;

class MyFacade extends Facade
{
    //...
}


  1. Implement the facade class: Extend the facade class with the base Laravel Facade class and implement the facade contract interface. Implement the required getFacadeAccessor() method that should return the name of the binding or class that the facade represents.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;
use App\Contracts\MyFacadeInterface;

class MyFacade extends Facade implements MyFacadeInterface
{
    protected static function getFacadeAccessor()
    {
        return 'my-facade'; // Return the binding or class name
    }

    // Implement required methods from the interface
    public static function method1()
    {
        return static::$app['my-facade']->method1();
    }

    public static function method2($param1, $param2)
    {
        return static::$app['my-facade']->method2($param1, $param2);
    }
    // Implement additional methods as needed
}


  1. Register the facade: Register the facade in the 'config/app.php' file under the 'aliases' array. Add an entry with the facade class name as the key and the facade class namespace as the value. For example:
1
2
3
4
'aliases' => [
    //...
    'MyFacade' => App\Facades\MyFacade::class,
]


That's it! You have now defined the contract for a Laravel facade. The facade class will act as a proxy to access the underlying functionality provided by the corresponding binding or class. You can now use the facade throughout your codebase to access the methods defined in the contract.


How to resolve dependencies using Laravel facades?

To resolve dependencies using Laravel facades, follow these steps:

  1. Import the facade class: Begin by importing the facade class at the top of your file using the use statement. For example, if you want to use the DB facade:
1
use Illuminate\Support\Facades\DB;


  1. Access the facade methods: You can now access the methods provided by the facade class. For example, to perform a database query using the DB facade:
1
$results = DB::select('select * from users');


  1. Resolving the dependencies: Laravel will automatically resolve the dependencies for you when using facades. For example, the DB facade in Laravel is resolved to an instance of the Illuminate\Database\Connection class. You don't need to manually instantiate or inject the dependencies.
  2. Configuring the facade: Sometimes, you might need to configure the facade before using it. You can do this by calling the ::shouldReceive() method and passing in the desired configuration values. For example, to set the database connection for the DB facade:
1
DB::shouldReceive('connection')->andReturn('mysql');


Keep in mind that facades should be used sparingly and primarily for convenience. If possible, it is recommended to use dependency injection instead of facades to manage your dependencies as it promotes better code organization and testability.


What is the purpose of Laravel facades?

The purpose of Laravel facades is to provide a "static" interface to classes that are available in the application's service container. Facades make it easy to access and use classes without the need for explicit dependency injection, thus simplifying the development process. Facades act as a proxy for the actual underlying implementation of a class, allowing developers to access its methods and properties using a clean and expressive syntax. This helps improve code readability and maintainability.


How to register a facade in Laravel?

To register a facade in Laravel, follow these steps:

  1. Open the config/app.php file.
  2. Locate the aliases array.
  3. Add a new entry to the array in the format 'AliasName' => 'Facades\Namespace\ClassName'. For example: 'FacadeName' => 'App\Facades\ExampleFacade'.
  4. Save the configuration file.


Next, you need to create the actual facade class. Follow these steps to create it:

  1. In your Laravel application's app directory, create a new directory called Facades if it doesn't exist.
  2. Inside the Facades directory, create a new PHP class file with the desired facade name, followed by "Facade". For example: ExampleFacade.php.
  3. In the facade class file, define the namespace according to your application's structure. For example: namespace App\Facades;.
  4. Add the necessary use statement to include the class you want to create a facade for.
  5. Extend the facade class with Illuminate\Support\Facades\Facade.
  6. Implement a protected static accessor method called getFacadeAccessor, which returns the class or binding you want to access through the facade. For example, protected static function getFacadeAccessor() { return 'example'; }, where 'example' refers to a service or container binding in your application.


That's it! You have successfully registered a facade in Laravel. You can now use the facade to access the underlying class or binding in your application.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

API authentication is an essential aspect of securing your Laravel application. Laravel provides various built-in mechanisms to implement API authentication effortlessly. One widely used method is to leverage Laravel Passport, a full OAuth2 server implementati...
To send and receive requests in real time using Laravel, you can utilize Laravel Echo along with Socket.io or Pusher for real-time communication.First, you need to set up Laravel Echo on the front end by installing Laravel Echo and Socket.io or Pusher through ...
To create a new Laravel project, you can follow these steps:Open your command-line interface (CLI) or terminal.Navigate to the directory where you want to create the Laravel project.Run the following command: composer create-project --prefer-dist laravel/larav...