如何在ServiceProvider中自动注册helpers类?

How to automatically register helpers class in ServiceProvider?(如何在ServiceProvider中自动注册helpers类?)
本文介绍了如何在ServiceProvider中自动注册helpers类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

In PHP how can you clear a WSDL cache?(在 PHP 中如何清除 WSDL 缓存?)
failed to open stream: HTTP wrapper does not support writeable connections(无法打开流:HTTP 包装器不支持可写连接)
Stop caching for PHP 5.5.3 in MAMP(在 MAMP 中停止缓存 PHP 5.5.3)
Caching HTTP responses when they are dynamically created by PHP(缓存由 PHP 动态创建的 HTTP 响应)
Memcached vs APC which one should I choose?(Memcached 与 APC 我应该选择哪一个?)
What is causing quot;Unable to allocate memory for poolquot; in PHP?(是什么导致“无法为池分配内存?在 PHP 中?)