samedi 2 juin 2018

Laravel 5.6 "Unresolvable dependency resolving..." when doing dependency injection

I am trying to bind a class into the container via a middleware and it doesn't seem to work because the class that I am binding recieved 2 parameters in the constructor and they aren't recognised.

Here is the middleware:

<?php

namespace App\Http\Middleware;

use App\Services\Factureaza;
use Closure;

class InitializeInvoiceProvider
{
    public function handle($request, Closure $next)
    {
        app()->singleton(Factureaza::class, function () {
            // get settings by calling a custom helper function
            $settings = json_decode(get_setting('invoicing_provider_settings'), true);
            $api_url = isset($settings['url']) ? $settings['url'] : null;
            $api_key = isset($settings['key']) ? $settings['key'] : null;
            return new Factureaza($api_url, $api_key);
        });

        return $next($request);
    }
}

The Factureaza class looks like this:

<?php

namespace App\Services;

use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;

class Factureaza
{
    protected $client;
    protected $base_url;
    protected $api_key;

    public function __construct($base_url, $api_key)
    {
        $this->client = new GuzzleClient([
            'base_uri' => $base_url,
            'verify' => false,
            'auth' => [$api_key, 'x'],
        ]);
        $this->base_url = $base_url;
        $this->api_key = $api_key;
    }
}

I am getting this error when I am trying to resolve the dependency in my controller:

<?php

class InvoicesController extends Controller
{
    protected $api;

    public function __construct()
    {
        $this->api = resolve('App\Services\Factureaza');
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire