Created
February 15, 2019 05:00
-
-
Save phptuts/03edc67376b2c2352294e925d6163331 to your computer and use it in GitHub Desktop.
PHP Adapter Pattern
This file contains hidden or 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 | |
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('[email protected]', '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