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 the composer.json
file. But I think this is not a good way, when you add more functions in the helpers.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 in app \Providers
generated in the file HelperServiceProvider.php
You can simply remove the boot()
method, we will not use it here.
In the register()
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 the app/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, open config/app.php
, and then put HelperServiceProvider
on top of your AppServiceProvider
...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 a Carbon.php
file in the app/Helpers
directory with the following code:
<?php/** * Carbon helper * * @param $time * @param $tz * * @return Carbon\Carbon */function carbon($time = null, $tz = null){ return new \Carbon\Carbon($time, $tz);}
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):
<?php/** * Carbon helper * * @param $time * @param $tz * * @return Carbon\Carbon */function carbon($time = null, $tz = null){ return new \Carbon\Carbon($time, $tz);}function carbonFormatted($time = null, $tz = null){ return carbon($time, $tz)->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!