Back in the day I used to load my helpers.php
file through composers files
array. That would still work absolutely fine, however I decided to move them in to the app directory and auto-load them with a service provider to take a more organizational approach.
This way I can organize my helpers by file name, and when I place them in my pre-configured directory I have global availability to the methods inside them.
HelperServiceProvider
:
So the first step is to create a new service provider called 1<?php 2 3namespace App\Providers; 4 5use Illuminate\Support\ServiceProvider; 6use RecursiveDirectoryIterator; 7use RecursiveIteratorIterator; 8 9class HelperServiceProvider extends ServiceProvider10{11 /**12 * Register bindings in the container.13 *14 * @return void15 */16 public function boot(): void17 {18 $rdi = new RecursiveDirectoryIterator(app_path('Helpers'.DIRECTORY_SEPARATOR.'Global'));19 $it = new RecursiveIteratorIterator($rdi);20 21 while ($it->valid()) {22 if (23 ! $it->isDot() &&24 $it->isFile() &&25 $it->isReadable() &&26 $it->current()->getExtension() === 'php' &&27 strpos($it->current()->getFilename(), 'Helper')28 ) {29 require $it->key();30 }31 32 $it->next();33 }34 }35}
app/Helpers/Global
.
Then create the directory which you have specified, in my case Now any file I place in app/Helpers/Global
will be auto-loaded for me, and will consist of specifically one-off functions, and not classes. Classes I would place in app/Helpers/XXXX
depending on the category. These would not be auto-loaded but are still good to have all in one place.
app.php
service providers array:
From there you want to load your new service provider in your 1/*2 * Application Service Providers...3 */4App\Providers\AppServiceProvider::class,5...6App\Providers\HelperServiceProvider::class,7...
Finally, create your first helper file:
For example, I usually create a GeneralHelper for things I can't find another category for:
app/Helpers/Global/GeneralHelper.php
1<?php 2 3use Carbon\Carbon; 4 5if (! function_exists('appName')) { 6 /** 7 * Helper to grab the application name. 8 * 9 * @return mixed10 */11 function appName()12 {13 return config('app.name');14 }15}16 17if (! function_exists('carbon')) {18 /**19 * Create a new Carbon instance from a time.20 *21 * @param $time22 *23 * @return Carbon24 * @throws Exception25 */26 function carbon($time)27 {28 return new Carbon($time);29 }30}
From this file I have access to appName()
and carbon()
from anywhere without having to load any classes:
I definitely use this approach sparingly as I don't want to have too much extra overhead. However, I've had projects with dozens and have yet to notice a difference even on a $5 droplet.