dimanche 29 octobre 2017

Using Laravel Service Container For Third Party APIs

I'm trying to make good use of Laravel's Service Container to instantiate a connection to a third party API and use it properly across my Controllers. Below is a Service I created and a basic Controller but it doesn't seem to be working the way I'd expect. Where am I going wrong? Should this be structured differently? How so?

namespace App\Services;

use App\Http\Clients\RestClient;

class RestApiService {

    private $api;

    /**
     * Return the API connection.
     *
     * @return array
     */
    public function connect() {

        $api = new RestClient();
        $api->setUrl(getenv('API_REST_URL'))
                    ->setUsername(getenv('API_USERNAME'))
                    ->setPassword(getenv('API_PASSWORD'))
                    ->connect();

        return $api;
    }
}

class UserController extends Controller {

    protected $api;

    public function __construct(RestApiService $api) {
        $this->api = $api;
    }

   public function index() {
        $users = $this->api->getUser(session('user_id'));

        return view('user.index', ['users' => $users]);
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire