Pramod Sivadas
Pramod Sivadas

Reputation: 893

Using Laravel Service Provider for passing constructor parameter

I am trying to use laravel service provider for injecting dependencies.

namespace App\ABC\Services;

use Exception;
use App\ABC\Models\Nsme;
use GuzzleHttp\Client;
use Illuminate\Http\Response;

class NsmeService
{

    /**
     * GuzzleHttp client
     *
     * @var $httpClient
     */
    protected $httpClient;

    /**
     * Create a new service instance.
     *
     * @param Nsme $nsme
     */
    public function __construct(Nsme $nsme)
    {
        $this->httpClient = $httpClient;
    }

    public function doApiCall() {
        new Client(['base_uri' => 'http://sso.myapiservice.com']);
    }   
}

In the above class I want to modify doApiCall to use service laravel provider.

My have written the service provider like this.

namespace App\ABC\Providers;

use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client;

class HttpClientServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    //protected $defer = false;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
       $this->app->bind('GuzzleHttp\Client', function()
        {
            return new Client(['base_uri' => 'http://sso.testserver.com']);
        });
    }   

Then I modified doApiCall() method like this

public function doApiCall() {
    $client = app('Client');
}   

But this is not working. Basically I want to pass some constructor parameters so I cannot pass the Client class as constructor parameter in NsmeService class. Any Ideas?

Upvotes: 0

Views: 1394

Answers (1)

xAoc
xAoc

Reputation: 3588

Try this.

$client = app('GuzzleHttp\Client');

You bind service like GuzzleHttp\Client but call like a Client. To avoid this kind mistake you can use \GuzzleHttp\Clint::class.

Also, don't forget to register your service provider :)

Upvotes: 1

Related Questions