Laravel-在服务提供商中需要php脚本 [英] Laravel - require php script in a service provider
问题描述
我对Laravel并不陌生,并在SO上使用此答案为我的助手功能实现了服务提供商. >
建议:
在新生成的注册功能中 HelperServiceProvider.php添加以下代码
require_once app_path('Helpers/AnythingHelper.php');
但是, Laravel文档指出,注册方法仅应为用于将东西绑定到容器中:
如前所述,在register方法中,您仅应 将东西绑定到服务容器中.你绝对不要尝试 注册任何事件侦听器,路由或其他任何内容 register方法中的功能.
就我而言,该应用程序按原样运行,但在register函数中需要一条语句,因此我的问题更多是关于最佳做法",而不是使代码正常工作.
问题:
这是一种好的/可以接受的方法(在register方法中使用require语句),还是我应该将require语句移到boot方法中?
如果仅在此处放置方法(而非类),则为推荐方法:
- 在任意位置创建文件
-
在
composer.json
中,请确保将此文件添加到autoload
内的files
键中,如下所示:"autoload": { // here other autoload things "files": ["app/Helpers/AnythingHelper.php"] },
-
运行
composer
dump-autoload`
对于类,显然应该使用标准的PSR-4自动加载
I am quite new to Laravel and implemented the service provider for my helper functions using this answer on SO.
It recommended to:
in the register function of your newly generated HelperServiceProvider.php add following code
require_once app_path('Helpers/AnythingHelper.php');
However, Laravel docs state that register method should only be used to bind things into the container:
As mentioned previously, within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method.
In my case the app works as it is, with require a statement in the register function, so my question is more about 'best practices' rather than making the code work.
Question:
Is this a good/acceptable approach (require statement in a register method), or should I rather move require statement to the boot method?
Recommended approach if you put here only methods (not classes):
- Create file anywhere you want
In
composer.json
make sure you add this file tofiles
key insideautoload
like this:"autoload": { // here other autoload things "files": ["app/Helpers/AnythingHelper.php"] },
Run
composer
dump-autoload`
For classes obviously you should use standard PSR-4 autoloading
这篇关于Laravel-在服务提供商中需要php脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!