简体   繁体   English

Laravel加载并初始化自定义帮助程序类

[英]Laravel load and initialize custom helper class

There are many questions regarding loading custom helper classes in Laravel. 关于在Laravel中加载自定义帮助程序类有很多问题。 However, none of them focus on the loading them with proper initialization. 但是,它们都不关注通过适当的初始化来加载它们。

As of Laravel version 5.3 we can use psr-4 autoloading which is autoloading the entire app/ directory. 从Laravel 5.3版本开始,我们可以使用psr-4自动加载功能,该功能可以自动加载整个app/目录。 However, classes are loading but never initialized. 但是,类正在加载但从未初始化。

I have my helper class inside the app/helpers/support.php . 我在app/helpers/support.php有我的帮助器类。 This class has a constructor, where I want to load some important configuration in order to make the helper usable. 此类有一个构造函数,我想在其中加载一些重要的配置以使助手可用。

So how can I load my helper but ALSO initialize it properly in Laravel? 那么,如何加载我的助手,但还要在Laravel中正确初始化它? Right now I am simply working-around the problem by using new \\App\\Helper\\Support(); 现在,我只是通过使用new \\App\\Helper\\Support();解决该问题new \\App\\Helper\\Support(); inside AppServiceProvider.php . AppServiceProvider.php


Edit: I'm using the following approach to maintain my helper class: 编辑:我正在使用以下方法来维护我的助手类:

Best practices for custom helpers on Laravel 5 Laravel 5上自定义助手的最佳实践

It seems like what you have is a service. 看来您拥有的是一项服务。 Rather than creating an instance, you can declare it in your app service provider and inject it as a dependency when you need it. 无需创建实例,而是可以在应用服务提供商中声明它,并在需要时将其作为依赖项注入。

In your register method: 在您的register方法中:

$this->app->bind(\App\Helper\Support::class);

You can now use dependency injection to get an instance of your class. 现在,您可以使用依赖注入来获取类的实例。 You can also make an instance like this: 您还可以创建一个这样的实例:

app()->make(\App\Helper\Support::class);

If you only want one instance to exist at any given time, use singleton rather than bind . 如果您只希望在任何给定时间存在一个实例,请使用singleton而不是bind

I recommend reading the service container documentation: 我建议阅读服务容器文档:

https://laravel.com/docs/5.5/container https://laravel.com/docs/5.5/container

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM