如何在ServiceProvider中自动注册助手类? [英] How to automatically register helpers class in ServiceProvider?
问题描述
我正在研究Laravel 5.1项目,并且已经开发了很多帮助程序.
有什么方法可以在ServiceProivder中自动注册帮助程序类,而不是手动添加它们?
我已经对其进行了研究,最后我通过将不同的谜题放在一起解决了该问题,从而解决了这个问题:
对于Laravel 5:
第1步.创建的文件夹app/Helpers
第2步.在app/Providers
文件夹中,使用以下artisan命令创建提供程序HelpersServiceProvider.php
:
php artisan make:provider HelpersServiceProvider
第3步.在HelpersServiceProvider.php
文件中,我们创建了一个foreach loop
内部寄存器函数,以获取所有此类的帮助程序类:
public function register()
{
foreach (glob(app_path() . '/Helpers/*.php') as $helpersfilename)
{
require_once($helpersfilename);
}
}
第4步.在config/app.php
行中添加
/*
* Application Service Providers added by developer...
*/
App\Providers\HelpersServiceProvider::class,
就是这样,这里的解决方案已经过测试,可以在Laravel 5.x的所有版本上使用.现在,您可以在helpers文件夹中添加无限的helper,它们将被自动添加到系统中.
Laravel 4 尚未经过测试,但是如果有人这样做,请为Laravel 4添加/编辑.
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?
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.
这篇关于如何在ServiceProvider中自动注册助手类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!