Home>Article>PHP Framework> 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.json
file. But I think this is not a good way, when you add more functions in thehelpers.php
file, 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 \Providers
generated 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/Helpers
directory, 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 putHelperServiceProvider
on 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.php
file in theapp/Helpers
directory with the following code:
You don't need to add any command spaces. If you want, you can use
function_exists
to detect whether this function exists.Now you can use the helper function
carbon()
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!