Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

php - How to automatically register helpers class in ServiceProvider?

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 adding them manually?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...
*/
AppProvidersHelpersServiceProvider::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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...