問題描述
我正在從事 Laravel 5.1 項目并開發了很多幫助程序.
I am working on Laravel 5.1 project and have developed a lot of helpers.
有沒有辦法在ServiceProivder中自動注冊helpers類,而不是手動添加?
Is there any way to automatically register helpers class in ServiceProivder in stead of adding them manually?
推薦答案
我一直在努力,最終通過將不同的謎題放在一起解決了這個問題:
I have worked on it and I finally fixed it by putting different puzzles together ending with this solution:
對于 Laravel 5:
步驟 1. 創建文件夾 app/Helpers
第 2 步. 在 app/Providers
文件夾中,使用以下工匠命令創建提供程序 HelpersServiceProvider.php
:
Step 2. In app/Providers
folder, create provider HelpersServiceProvider.php
using following artisan command:
php artisan make:provider HelpersServiceProvider
第 3 步. 在 HelpersServiceProvider.php
文件中,我們在 register 函數中創建一個 foreach 循環
來獲取所有 helpers 類,如下所示:
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);
}
}
第 4 步. 在 config/app.php
中添加以下行
/*
* Application Service Providers added by developer...
*/
AppProvidersHelpersServiceProvider::class,
就是這樣,這里的解決方案已經過測試,適用于所有版本的 Laravel 5.x.現在你可以在 helpers 文件夾中添加無限的助手,它們會自動添加到系統中.
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 尚未測試,但如果有人這樣做,請為 Laravel 4 添加/編輯此內容.
Laravel 4 is not tested yet, but if some body do it, please add/edit this for Laravel 4.
這篇關于如何在ServiceProvider中自動注冊helpers類?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!