Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

laravel - Understand a concept, is Service Provider the correct use case?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A service provider adds services to the service (IoC) container.

In your case, it seems you want code that gets data from third-party providers in a consistent manner. So you probably want to define an interface for this, and then have individual classes that implement that interface (i.e. GithubProjectRepository, BitbucketProjectRepository, etc).

You’d probably use a service provider to register configured instances of GitHub, Bitbucket’s, etc SDKs. This would be instantiated and configured from your config files. You can then type-hint these SDKs in your class’s constructors and the container will give you configured instances instead of having to new-up all over your application.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...