2

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?

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Amade
  • 3,665
  • 2
  • 26
  • 54

1 Answers1

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

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • so you'd say to ditch the service provider approach altogether for things like helper functions and handle it through composer, right? – Amade Nov 02 '17 at 17:08
  • 1
    If you have file with simple functions I don't see any point to use service provider, you can use composer to autoload those files. The same thing is done in Laravel for helper files. Just look at https://github.com/laravel/framework/blob/5.5/composer.json and you will see `src/Illuminate/Foundation/helpers.php"` loaded in this way – Marcin Nabiałek Nov 02 '17 at 17:10
  • makes sense, I'll handle it through composer then :) but theoretically assuming I'd want to keep it in the service provides, should the require statement be moved to the boot method? I just want to make sure that I understand the docs correctly on this end - is doing anything other than binding things (i.e. using bind, singleton, instance etc. methods of app) to the container a big 'no no' in the register method? Should anything else be moved to the boot method by default? – Amade Nov 02 '17 at 17:20