Home>Article>PHP Framework> How to add custom facade and service provider using laravel

How to add custom facade and service provider using laravel

little bottle
little bottle forward
2019-04-29 10:35:25 3433browse

When using PHP’s laravel framework for project development, we often use the facade and Service provider, let's explore how to write your own facade and service provider (the following code is based on laravel 5.2*).

1. Create a custom class

Create a utils\ToolBar.php file under the app directory. This is our tool class, which contains the code we defined. .


      

2. Create a service provider

Execute the command in the root directory of the project: php artisan make:provider ToolServiceProvider to create a service provider and add what we just The tool class written is registered in the container.

app->bind('tool',function(){ return new ToolBar(); }); }}

3. Group registration service provider

Register the service provider we just added in the providers attribute in the config\app.php file, that is, add:

App\Providers\ToolServiceProvider::class,

4. Create a facade class

Create a facade class under the app directory, App\Facades\Tool.php, the directory here is created by myself, this You can create whatever you want. As long as it is consistent when registering later, it will be fine. The code is as follows:


      

5. Group registration facade class

Add the following code to the aliases attribute of config\app.php:

'Tool' => App\Facades\Tool::class,

After completing the above steps, we can call to test whether the created facade and service provider are valid
Add the following code in routes\console.php:

Artisan::command('testFacade',function(){ dd(tool::get());});

Then in the terminal of the project root directory, call The following command:

php artisan testFacade

If Hello my facade is output, it means the registration is successful. Next, we can use the custom facade anywhere in the project.

When using PHP's laravel framework for project development, we often use the facade and service providers that come with the laravel framework. , let's explore how to write our own facade and service provider (the following code is based on laravel 5.2*).

Related tutorials:laravel video tutorial

The above is the detailed content of How to add custom facade and service provider using laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete