Skip to content

Instantly share code, notes, and snippets.

@gemmadlou
Created April 3, 2017 10:41
Show Gist options
  • Select an option

  • Save gemmadlou/5f86a0cfc718e768af643656e07c027a to your computer and use it in GitHub Desktop.

Select an option

Save gemmadlou/5f86a0cfc718e768af643656e07c027a to your computer and use it in GitHub Desktop.
Hexagonal Architecture
<?php namespace Example\Model;
use App\Utility\Escape;
/**
* Post promo view model.
*/
class ArticlePromoView
{
const numberOfWords = 18;
private $day;
private $monthYear;
private $title;
private $excerpt;
private $content;
private $url;
public function __construct($day, $monthYear, $title, $excerpt, $content, $url)
{
$this->day = $day;
$this->monthYear = $monthYear;
$this->title = $title;
$this->excerpt = $excerpt;
$this->content = $content;
$this->url = $url;
}
/**
* Gets day of article
* @return string
*/
public function getDay()
{
return Escape::string($this->day);
}
/**
* Gets month and year of article
* @return string
*/
public function getMonthYear()
{
return Escape::string($this->monthYear);
}
/**
* Gets title of article
* @return string
*/
public function getTitle()
{
return Escape::string($this->title);
}
/**
* Gets blurb of article
* @return string
*/
public function getBlurb()
{
return ($this->excerpt)
? wp_trim_words(Escape::allTags($this->excerpt), self::numberOfWords)
: wp_trim_words(Escape::allTags($this->content), self::numberOfWords);
}
/**
* Gets url of article
* @return string
*/
public function getURL()
{
return Escape::url($this->url);
}
}
<?php namespace Example\Model;
interface RecentPostRepository {
/**
* Finds the recent posts but omits excluded ones
* @param array $excludedPostIds Array of post ids to exclude. One is sufficient
* @return PostPromoView promo view model
*/
public function findWhileExcluding(array $excludedPostIds);
}
<?php namespace Example\Repository\Wordpress;
use Example\Model\RecentPostRepository;
use Example\Model\ArticlePromoView;
/**
* Gets recent posts
*/
class WordpressRecentPostRepository implements RecentPostRepository {
public function findWhileExcluding(array $excludedPostIds)
{
$posts = get_posts([
'post__not_in' => $excludedPostIds,
'posts_per_page' => 2
]);
return $this->mapPosts($posts);
}
/**
* Converts posts data into our domain view models
* @param array $posts
* @return array of ArticlePromoView
*/
private function mapPosts($posts)
{
$mappedPosts = collect($posts)->map(function($post) {
return new ArticlePromoView(
get_the_time('j', $post->ID),
get_the_time('F y', $post->ID),
$post->post_title,
$post->post_excerpt,
$post->post_content,
get_permalink($post->ID)
);
})->toArray();
return $mappedPosts ? $mappedPosts : [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment