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*).
Create a utils\ToolBar.php file under the app directory. This is our tool class, which contains the code we defined. .
<?phpnamespace App\Utils;class ToolBar{ public function get() { return 'Hello my facade'; }}
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.
<?phpnamespace App\Providers;use Illuminate\Support\ServiceProvider;use App\Utils\ToolBar;class ToolServiceProvider extends ServiceProvider{ /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('tool',function(){ return new ToolBar(); }); }}
Register the service provider we just added in the providers attribute in the config\app.php file, that is, add:
App\Providers\ToolServiceProvider::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:
<?phpnamespace App\Facades;use Illuminate\Support\Facades\Facade;class Tool extends Facade{ protected static function getFacadeAccessor() { return 'tool'; }}
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!