Skip to content

Instantly share code, notes, and snippets.

@phptuts
Created February 15, 2019 05:00
Show Gist options
  • Save phptuts/03edc67376b2c2352294e925d6163331 to your computer and use it in GitHub Desktop.
Save phptuts/03edc67376b2c2352294e925d6163331 to your computer and use it in GitHub Desktop.
PHP Adapter Pattern
<?php
class AuthSystem {
/**
* @var EmailLoginInterface
*/
private $login;
public function __construct(EmailLoginInterface $login)
{
$this->login = $login;
}
public function auth($username, $password)
{
return $this->login->login($username, $password);
}
}
class Credential {
private $data;
public function __construct($data)
{
$this->data = $data;
}
}
interface EmailLoginInterface {
/**
* @param $username
* @param $password
* @return Credential
*/
public function login($username, $password): Credential;
}
class EmailLogin implements EmailLoginInterface {
public function login($username, $password): Credential
{
return new Credential('LOGIN CREDENTIAL');
}
}
interface TokenLoginInterface {
public function authToken($token): Credential;
}
class JWTLogin implements TokenLoginInterface {
public function authToken($token): Credential
{
return new Credential('Auth JWT ' . $token);
}
}
class AmazonLogin implements TokenLoginInterface {
public function authToken($token): Credential
{
return new Credential('Amazon Token ' . $token);
}
}
class TokenAdapter implements EmailLoginInterface {
/**
* @var TokenLoginInterface
*/
private $tokenLogin;
public function __construct(TokenLoginInterface $tokenLogin)
{
$this->tokenLogin = $tokenLogin;
}
public function login($username, $password): Credential
{
return $this->tokenLogin->authToken($username);
}
}
var_dump((new AuthSystem(new EmailLogin()))->auth('bill@gmail.com', 'pass'));
var_dump((new AuthSystem(new TokenAdapter(new JWTLogin())))->auth('TOKEN', null));
var_dump((new AuthSystem(new TokenAdapter(new AmazonLogin())))->auth('AMAZON TOKEN', null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment