Created
September 19, 2018 19:26
-
-
Save acidjazz/99d7f4884ba18f6da59b613120cb9244 to your computer and use it in GitHub Desktop.
classs vs arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// OLD | |
class Foo | |
{ | |
public function getVideosA($ids) | |
{ | |
$videos = []; | |
$list = $this->youtube->videos->listVideos( | |
['statistics,snippet'], | |
['id' => implode(',', $ids), 'maxResults' => count($ids)] | |
); | |
foreach ($list->items as $item) { | |
$videos[$item->id] = [ | |
'id' => $item->id, | |
'title' => $item->snippet->title, | |
'views' => $item->statistics->viewCount, | |
]; | |
} | |
return $videos; | |
} | |
} | |
// NEW | |
class Video | |
{ | |
/** Snippet */ | |
private $snippet; | |
/** Statistics */ | |
private $statistics; | |
public function __construct(int $id, Snippet $snippet, Statistics $statistics) | |
{ | |
$this->id = $id; | |
$this->snippet = $snippet; | |
$this->statistics = $statistics; | |
} | |
public function getSnippet(): Snippet | |
{ | |
return $this->snippet; | |
} | |
public function getStatistics(): Statistics | |
{ | |
return $this->statistics; | |
} | |
} | |
class Snippet | |
{ | |
/** string */ | |
private $title; | |
public function __construct(string $title) | |
{ | |
$this->title = $title; | |
} | |
public function getTitle(): string | |
{ | |
return $this->title; | |
} | |
} | |
class Stastistics | |
{ | |
/** int */ | |
private $viewCount; | |
public function __construct(int $viewCount) | |
{ | |
$this->viewCount = $viewCount; | |
} | |
public function getViewCount(): int | |
{ | |
return $this->viewCount; | |
} | |
} | |
class Bar | |
{ | |
/** | |
* @param int[] $ids | |
* @return Video[] | |
*/ | |
public function getVideos(array $ids): array | |
{ | |
$list = $this->youtube->videos->listVideos( | |
['statistics,snippet'], | |
['id' => implode(',', $ids), 'maxResults' => count($ids)] | |
); | |
return array_reduce( | |
$list, | |
function (array $carrier, Model $item) { | |
return $carrier[$item->id] = new Video( | |
$item->id, | |
new Snippet($item->snippet->title), | |
new Statistics($item->statistics->viewCount) | |
); | |
}, | |
[] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment