Home>Article>PHP Framework> How does Laravel include its own helper functions?

How does Laravel include its own helper functions?

Guanhui
Guanhui forward
2020-06-24 18:00:39 2813browse

How does Laravel include its own helper functions?

#Many tutorials will say that you can achieve this requirement by adding an automatically loaded file to thecomposer.jsonfile. But I think this is not a good way, when you add more functions in thehelpers.phpfile, the readability will become poor.

Below I will introduce a way that allows you to define many files to contain different functions. This will make our program cleaner and more readable.

Let’s get started

First create a HelperServiceProvider.php service provider file:

php artisan make:provider HelperServiceProvider

Use the above command, you will be inapp \Providersgenerated in the fileHelperServiceProvider.php

You can simply remove theboot()method, we will not use it here.

In theregister()method we add the following code:

public function register(){ foreach (glob(app_path('Helpers') . '/*.php') as $file) { require_once $file; }}

This loop will traverse all the files in theapp/Helpersdirectory, As you may have guessed, now you can create any files in this directory and they will be loaded into your application. These helper functions will be accessible from anywhere in your code (views, models, controllers… )

We also need to load this service provider, openconfig/app.php, and then putHelperServiceProvideron top of yourAppServiceProvider

...App\Providers\HelperServiceProvider::class,App\Providers\AppServiceProvider::class,App\Providers\AuthServiceProvider::class,App\Providers\BroadcastServiceProvider::class,...

Now let us create a simple function and create aCarbon.phpfile in theapp/Helpersdirectory with the following code:


      

You don't need to add any command spaces. If you want, you can usefunction_existsto detect whether this function exists.

Now you can use the helper functioncarbon()anywhere in your application. Now, if you need another function that returns a specific format (just for the use case of this tutorial), you can enter that function in the same file (Carbon.php):

format('Y-m-d')}

Okay! Now you can start populating the app/Helpers directory with your own PHP files containing your frequently used helpers

NOTE: Please keep in mind that I am Dutch and English is not mine My native language, therefore this article may contain some grammatical errors.

Recommended tutorial: "Laravel Tutorial"

The above is the detailed content of How does Laravel include its own helper functions?. For more information, please follow other related articles on the PHP Chinese website!

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