Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adapter pattern real life example
<?php
interface SocialInterface
{
public function getFriends();
public function getPosts();
}
class Facebook implements SocialInterface
{
public function getFriends()
{
var_dump("get all facebook friends");
}
public function getPosts()
{
var_dump("get all facebook posts");
}
}
class Twitter
{
public function getFollowers()
{
var_dump("get Twitter followers");
}
public function getTweets()
{
var_dump("get all twitter tweets");
}
}
class TwitterAdapter implements SocialInterface
{
/**
* @var Twitter
*/
protected $twitter;
public function __construct( Twitter $twitter )
{
$this->twitter = $twitter;
}
public function getFriends()
{
$this->twitter->getFollowers();
}
public function getPosts()
{
$this->twitter->getTweets();
}
}
class LinkedIn
{
public function getConnections()
{
var_dump("get all linkedin connections");
}
public function getFeeds()
{
var_dump("get all linkedin feeds");
}
}
class LinkedInAdapter implements SocialInterface
{
/**
* @var LinkedIn
*/
protected $linkedIn;
public function __construct( LinkedIn $linkedIn )
{
$this->linkedIn = $linkedIn;
}
public function getFriends()
{
$this->linkedIn->getConnections();
}
public function getPosts()
{
$this->linkedIn->getFeeds();
}
}
class Person
{
public function social( SocialInterface $social )
{
$social->getPosts();
$social->getFriends();
}
}
$person = new Person();
$person->social(new Facebook());
$person->social(new TwitterAdapter(new Twitter()));
$person->social(new LinkedInAdapter(new LinkedIn()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.