Laravel - require php script in a service provider

隐身守侯 提交于 2019-12-24 07:49:54

问题


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?


回答1:


Recommended approach if you put here only methods (not classes):

  1. Create file anywhere you want
  2. In composer.json make sure you add this file to files key inside autoload like this:

    "autoload": {
        // here other autoload things
    
        "files": ["app/Helpers/AnythingHelper.php"]
    },
    
  3. Run composerdump-autoload`

For classes obviously you should use standard PSR-4 autoloading



来源:https://stackoverflow.com/questions/47080137/laravel-require-php-script-in-a-service-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!