mardi 9 août 2016

best practice when implementing third party packages (youtube API) PHP

Intro

Hi all im looking to improve the quality of code and would love to hear your opinion on how I tackled a recent client's request.

if you feel I have taken the wrong approach, broken the SOLID Principles or you know how I could improve my code, please let me know, brutal and honest comments are welcome.

The request/challenge

The client requested a YouTube feed to be displayed on the home page.

My approach

First I pulled in a package called "php-youtube-api" with composer.

Instead of instantiating the package directed I created a YoutubeApiAdapter class which implements a VideoApiInterface

When I call getLatestVideos() there would be some call on the youtubeApi property (i've removed the logic to make this easier to read)

when I get a set of results back from the call I pass them into a YoutubeVideoAdapter class which implements a VideoInterface

the end result of calling getLatestVideos() would be an array of YoutubeVideoAdapter objects.

YoutubeApiAdapter

use Madcoda\Youtube;

class YoutubeApiAdapter implements VideoApiInterface
{

protected $youtubeApi;

public function __construct(Youtube $youtubeApi)
{
    $this->youtubeApi = $youtubeApi;
}

public function getLatestVideos()
{
    Some calls to the YouTube API to get the data her...
    $results = $this->youtubeApi->SOME_METHOD->SOME_RESULTS

    $data = [];

        foreach ($results as $result){
            $data[] = new YoutubeVideoAdapter($result);
        }

    return $data;
}

}

VideoApiInterface

interface VideoApiInterface
{
    public function getLatestVideos();
}

YoutubeVideoAdapter

class YoutubeVideoAdapter implements VideoInterface
{

protected $youtubeVideoObject;

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

public function getTitle()
{
    return $this->youtubeVideoObject->SOME_METHOD->SOME_RESULT
}

}

VideoInterface

interface VideoInterface
{
    public function getTitle();
}

Thank you for taking the time to read and review my post. All comments are welcome.

Aucun commentaire:

Enregistrer un commentaire