问题描述
我正在从事 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类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!