Initialize helper class in Laravel

Viewed 1812

I wrote a simple helper class, placed it in app\Helpers\MyHelper.php and created an alias for it in the app.php configuration file:

    'MyHelper' => App\Helpers\MyHelper::class,

The problem is that, now I need to use the class constructor to initialize some default values in it. However, the __construct function will never get called. Obviously, since it never gets initialized.

The question is, how (or where) can I initialize the helper class properly, so it could initialize it's default values?

My first thought: AppServiceProvider.php file and the boot() function.

I have placed a new MyHelper(); line there and it's working, however I'm wondering if this is a proper way doing it?

2 Answers

You can create helper class has static class so there no need to create instance of the class for example

<?php

namespace App\Helpers;

class HelperFunction {

    public static function createGroup() {

}

so you can import class it in your controller using use keyword and access like

HelperFunction::createGroup();

In general Services Providers are there for bootstrapping your application. The documentation doesn't say much about the AppServiceProvider but it seems to be there to bootstrap your app in general.

If you want to go the safe route you can create a new Service Provider by using php artisan make:provider MyHelperServiceProvider and add it in the providers array in your config/app.php file.

It looks identical to the AppServiceProvider but depending on your current code base it could be cleaner to put that helper into its own Service Provider.

I'm also just a beginner but to me both seem to be fine.

update: okay, found the important part in the docs: https://laravel.com/docs/5.5/lifecycle

The last paragraph says:

By default, the AppServiceProvider is fairly empty. This provider is a great place to add your application's own bootstrapping and service container bindings. Of course, for large applications, you may wish to create several service providers, each with a more granular type of bootstrapping.

Related