search
HomePHP FrameworkLaravelWhat is the use of laravel facade?

In laravel, facades are used to provide a static interface for the classes of the application's IoC service container. Laravel's facade serves as a static proxy for the underlying classes in the service container. Compared with traditional static methods, Provides easier-to-test syntax during maintenance.

What is the use of laravel facade?

The operating environment of this tutorial: Windows 10 system, Laravel 6 version, DELL G3 computer.

What is the use of laravel facade

Introduction

Facades provides a static interface for the application's IoC service container class. Laravel comes with some Facades, such as Cache, etc. Laravel's facade serves as a "static proxy" for the underlying class in the service container. Compared with traditional static methods, it can provide easier to test, more flexible, concise and elegant syntax during maintenance.

Explanation

In the context of Laravel application, a Facade is a class. Using this class, you can access an object from the container. This function is in the Facade defined in the class. Laravel's Facades and any Facades you define yourself will inherit the Facade class.

Your Facade class only needs to implement one method: getFacadeAccessor. Whatever needs to be resolved in the container is done in this method. The Facade base class uses the __callStatic() magic method, which can delay calls from Facade to the resolved object.

So, when you use Facade to call, like this: Cache:get, laravel will resolve the cache management class from the Ioc service container, and then call the get method on this class. Laravel's Facades can be used to locate services, which is a more convenient syntax for using Laravel's IoC service container.

Advantages

Facade has many advantages. It provides a simple and easy-to-remember syntax, allowing us to use Laravel provided without having to remember long class names. Functional features, in addition, make them easy to test due to their unique use of PHP's dynamic methods.

Actual use

The following example is used to call Laravel's cache system. Take a look at the following line of code first. You may think that this is a direct call to a static method called get on the Cache class.

$value = Cache::get('key');

However, if you look at the Illuminate\Support\Facades\Cache class, you will find that there is no get static method at all:

class Cache extends Facade {
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'cache'; }
}

The Cache class inherits the Facade base class , which defines a method called getFacadeAccessor(). Note that what this method does is to return an Ioc binding name, here it is cache.

When the user references any static method on the Cache Facade, Laravel will resolve the cache binding from the Ioc service container and execute the requested method on the object. (Here is the get method).

So, when we call Cache::get, what it really means is this:

$value = $app->make('cache')->get('key');

Import Facades

Note, When using facade, if a namespace is used in the controller, you need to import the Facade class into this namespace. All Facades are under the global namespace:

<?php namespace App\Http\Controllers;
use Cache;
class PhotosController extends Controller {
    /**
     * Get all of the application photos.
     *
     * @return Response
     */
    public function index()
    {
        $photos = Cache::get(&#39;photos&#39;);
        //
    }
}

Create Facades

You only need three things to create a Facade:

  • An IoC binding.

  • A Facade class.

  • Configuration of a Facade alias.

Below we define a class: PaymentGateway\Payment.

namespace PaymentGateway;
class Payment {
    public function process()
    {
        //
    }
}

We need to be able to resolve this class in the Ioc service container. Therefore, first add a Service Provider binding:

App::bind(&#39;payment&#39;, function()
{
    return new \PaymentGateway\Payment;
});

The best way to register this binding is to create a new Service Provider, name it PaymentServiceProvider, and then bind it to register method. Then configure laravel and load your Service Provider in the configuration file config/app.php.

The next step is to create your own Facade class:

use Illuminate\Support\Facades\Facade;
class Payment extends Facade {
    protected static function getFacadeAccessor() {
             return &#39;payment&#39;; 
    }
}

Finally, if you like, you can add an alias to the Facade and put it in the aliases array in the config/app.php configuration file inside.

You can call the process method on an instance of the Payment class. Like this:

Payment::process();

[Related recommendations: laravel video tutorial]

The above is the detailed content of What is the use of laravel facade?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

What versions of laravel are there? How to choose the version of laravel for beginnersWhat versions of laravel are there? How to choose the version of laravel for beginnersApr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravelHow to view the version number of laravel? How to view the version number of laravelApr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The latest method of using php framework laravelThe latest method of using php framework laravelApr 18, 2025 pm 12:57 PM

Laravel is a popular PHP-based web application framework that is popular among developers for its elegant syntax and powerful features. Its latest version introduces many improvements and new features designed to improve the development experience and application performance. This article will dive into Laravel's latest approach, focusing on how to leverage these updates to build more powerful and efficient web applications.

Laravel framework installation methodLaravel framework installation methodApr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to learn Laravel How to learn Laravel for freeHow to learn Laravel How to learn Laravel for freeApr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.