Best way to use 3rd party API data in a Laravel app
I'm building an app that will make use of several 3rd party API's that return roughly the same data for different types of objects.
For example, lets imagine I'm building an app to display data about different types of vehicles. Each manufacturer was kind enough to provide an API that returns data about their cars. The format of the data returned differ slightly, but they all contain the same information.
Would using contextual binding be a good idea for this? For example doing the following:
<?php
abstract class AbstractManufacturerController
{
protected $manufacturerService;
public function __construct(ManufacturerServiceInterface $manufacturerService)
{
$this->manufacturerService = $manufacturerService;
}
public function getResult($carModel)
{
return $this->manufacturerService->getCar($carModel);
}
}
// In routes.php file we can point url like: http://example.com/cars/mercedes/?carmodel=ml350 to use
// something like this: Route::resource('cars/mercedes', 'MercedesManufacturersController', ['only' => ['index']]);
class MercedesManufacturerController extends AbstractManufacturerController
{
// ...
}
// In routes.php file we can point url like: http://example.com/cars/audi/?carmodel=a3 to use
// something like this: Route::resource('cars/audi', 'AudiManufacturerController', ['only' => ['index']]);
class AudiManufacturerController extends AbstractManufacturerController
{
// ...
}
interface ManufacturerServiceInterface
{
public function getCar($carModel);
}
class MercedesManufacturerRepo implements ManufacturerServiceInterface
{
public function getCar($carModel)
{
// Get car data from Mercedes API
}
}
class AudiManufacturerRepo implements ManufacturerServiceInterface
{
public function getCar($carModel)
{
// Get car data from Audi API
}
}
$this->app->when('MercedesManufacturerController')->needs('ManufacturerServiceInterface')->give('MercedesManufacturerRepo');
$this->app->when('AudiManufacturerController')->needs('ManufacturerServiceInterface')->give('AudiManufacturerRepo');
I would set a base abstract class with all the required methods and checks etc that all car specific classes extend. Then implement each specific implementation in a more specific class.
Like the laracasts video on campaign monitor and/or laravels socialite plugin.