lundi 11 janvier 2016

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://ift.tt/1ScFuZF']);
    }   
}

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://ift.tt/1ScFuZH']);
        });
    }   

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire