Asif
Asif

Reputation: 35

Laravel 11: ServiceProvider Instantiation: Confused about how to use ServiceProvider

I have a serviceprovider defined in App\Libraries\NewPackage\src\CustomServiceProvider.php

In my composer.json I have

"autoload": {
        "psr-4": {
"NewPackage\\": "app/Libraries/NewPackage/src/"
}

In my bootstrap/providers.php I have

return [
    NewPackage\CustomServiceProvider::class,
];

In my ActionController.php, if I explicitly instantiate CustomServiceProvider, it works when I typehint it in a controller function- like this -->

public function __construct(){
        app()->bind(CustomServiceProvider::class, function($app) {
            return new CustomServiceProvider($app);
        });

    }

public function doSomething(Request $request, CustomServiceProvider $servicep)
    {
$servicep->somefunction();
}

However, without the instantiation if I try to obtain an instance of CustomServiceProvider, it fails with error-> 'Unresolvable dependency' Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Illuminate\Support\ServiceProvider

Here is the code that fails

private $servicep;

public function __construct(){
        $servicep = app()->make('NewPackage\CustomServiceProvider');
    }

public function doSomething(Request $request)
    {
      $servicep->somefunction();
}

I was thinking registering the CustomServiceProvider in bootstrap/provider.php was equivalent to instantiating the ServiceProvider. Else, what is the use of listing a class in bootstrap/provider.php Or, Am I doing something fundamentally wrong? In which part of the code?

Upvotes: 0

Views: 144

Answers (0)

Related Questions