问题
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):
- 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
来源:https://stackoverflow.com/questions/47080137/laravel-require-php-script-in-a-service-provider