How to automatically register helpers class in ServiceProvider?

后端 未结 1 1912
攒了一身酷
攒了一身酷 2020-12-16 08:39

I am working on Laravel 5.1 project and have developed a lot of helpers.

Is there any way to automatically register helpers class in ServiceProivder in stead of addi

相关标签:
1条回答
  • 2020-12-16 09:16

    I have worked on it and I finally fixed it by putting different puzzles together ending with this solution:

    For Laravel 5:

    Step 1. Created folder app/Helpers

    Step 2. In app/Providers folder, create provider HelpersServiceProvider.php using following artisan command:

    php artisan make:provider HelpersServiceProvider
    

    Step 3. In HelpersServiceProvider.php file, we make a foreach loop inside register function to fetch all helpers classes like this:

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

    Step 4. In config/app.php added following line

    /*
    * Application Service Providers added by developer...
    */
    App\Providers\HelpersServiceProvider::class,
    

    That is it, the solution here is tested and works on all versions of Laravel 5.x. Now you can add unlimited helpers in helpers folder, they will be automatically added to the system.

    Laravel 4 is not tested yet, but if some body do it, please add/edit this for Laravel 4.

    0 讨论(0)
提交回复
热议问题