Home PHP Framework Laravel Usage of service provider and facade pattern (Facade) in Laravel framework (code)

Usage of service provider and facade pattern (Facade) in Laravel framework (code)

Jul 31, 2018 pm 06:00 PM
facades laravel php

laravel framework It is very convenient to use the related operations of the built-in file system, so how is this implemented? In the next article, php Chinese website will give you a detailed explanation of the principles involved. Without further ado, let’s look directly at the content of the article.

Let’s start with an introduction:

Take the file system that comes with Laravel as an example. In the providers array of the configuration file in config/app.php, Registered a service provider:

IlluminateFilesystemFilesystemServiceProvider::class,
Copy after login

Defined a facade in the alias array:

‘File’ => IlluminateSupportFacadesFile::class,
Copy after login

Through these two steps, we can very conveniently use the file system related information provided by Laravel operation, and the calling form is very simple, such as:

File::exist($path) to determine whether the file exists.

File::get($path, $lock = false), get the contents of a file.

File::append($path, $data), append the content to the end of a file.

File::files($directory), get all the files in a directory.

Let’s talk about Laravel’s service provider and facade mode respectively.

Service provider

Let’s take a look at the definition first:

Service provider is all Laravel The central location where applications are launched. All core Laravel services, including your own applications, are started through service providers.

In the file system service provider, located at /vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemServiceProvider.php, the register method can see that a singleton is bound:

protected function registerNativeFilesystem()
{
    $this->app->singleton('files', function () {
        return new Filesystem;
    });
}
Copy after login

This singleton is the singleton mode of the Filesystem class. Of course, this service provider can also bind other singletons or do more things. We only study the principle of the File::exist() calling method here.

So there is a single instance of files, which is actually an instance of the Filesystem class.

At this time, if there is no Facade, you can also call the method of the Filesystem instance, that is, call it like this:

app(‘files’)->exist($path)
Copy after login

Okay, now let’s talk about the Facade.

Facade Facade pattern

Facades provide a "static" interface for classes available in the application's service container. Laravel comes with many facades, which can be used to access almost all of its services. Laravel facades They are the "static proxies" of the base classes in the service container. Compared with traditional static method calls, facades not only provide a simpler and richer syntax, but also have better testability and scalability.

At the beginning of this article, we mentioned that the alias array defines a File. The specific class is

IlluminateSupportFacadesFile::class,

its content is:

class File extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'files';
    }
}
Copy after login

It actually returns a name. Note that this name files is not the name of the singleton mode just bound? That's right.

In this way, you can use the File alias or facade to call methods in this Filesystem instance.

Through this article, I hope everyone can understand the relationship between service providers, Facade, and instances of the actually called classes.

The above is the entire content of this article. For more laravel content, please pay attention to the laravel framework introductory tutorial.

Recommended related articles:

Auxiliary functions in the Laravel framework: Introduction to the optional () function

Laravel5 .5 New feature: Analysis of preset command

Related course recommendations:

Recommended five latest Laravel video tutorials in 2017

The above is the detailed content of Usage of service provider and facade pattern (Facade) in Laravel framework (code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

Explain strict types (declare(strict_types=1);) in PHP. Explain strict types (declare(strict_types=1);) in PHP. Apr 07, 2025 am 12:05 AM

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values ​​to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

See all articles