I have created a service provider that takes data from GITHUB API and stores it in a table in a database. Quite a simple thing but I'm wondering if is this how I'm should be using Service Providers?
The second question is about extending this, in reality I want to add more platforms and API's that do this (I currently have one other platform working) but I currently have it set up as a separate service provider. There's a lot of similarities, only some differences in what the API data returns - I feel like I should be abiding by DRY but think this could get complicated when more and more API's get added (def not KISS).
I really want to confirm this before I spend more time extending this platform so appreciate any advice!
<?php
namespace AppProviders;
use GuzzleHttpClient;
use AppProjects;
use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesCache;
use IlluminateSupportFacadesAuth;
class GithubServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
$this->app->singleton('github_client', function ($app) {
try {
$client = new Client();
$code = $_GET['code'] ?? false;
$res = $client->post('https://github.com/login/oauth/access_token', [
'headers' => [
'Accept' => 'application/json',
],
'query' => [
'client_id' => env('GITHUB_ID'),
'client_secret' => env('GITHUB_SECRET'),
'code'=>$code
]
]
);
} catch(GuzzleHttpExceptionRequestException $e) {
$response = $e->getResponse();
throw new AppExceptionsCustomException($response->getStatusCode());
}
$username = Auth::user()->username;
$user_id = Auth::user()->id;
if($res->getBody() && !isset(json_decode($res->getBody())->error)):
$access_token = json_decode($res->getBody())->access_token;
$projects = json_decode($client->get('https://api.github.com/user/repos', [
'headers' => [
'Authorization'=> 'token ' . $access_token
]
])->getBody());
$i = 0;
foreach($projects as $project):
$i++;
// dd($project->images);
Projects::updateOrCreate(
[
'platform' => 'github',
'user_id' => $user_id,
'project_id' => $project->id
],
[
'platform' => 'github',
'sorting' => $i,
'user_id' => $user_id,
'title' => $project->name,
'description' => strip_tags($project->description),
'images' => '',
'url' => $project->html_url,
'project_id' => $project->id
]
);
endforeach;
endif;
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
question from:
https://stackoverflow.com/questions/66066475/understand-a-concept-is-service-provider-the-correct-use-case 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…