Skip to content

Instantly share code, notes, and snippets.

@altayalp
Created July 31, 2016 12:36
Show Gist options
  • Save altayalp/b4ee10c560d41dc197c2b86cc20ee54e to your computer and use it in GitHub Desktop.
Save altayalp/b4ee10c560d41dc197c2b86cc20ee54e to your computer and use it in GitHub Desktop.
Php facade design pattern simple and complete example with dependency injection
<?php
class Validate implements ValidateInterface
{
public function isValid(array $data)
{
return true;
}
}
class Auth implements AuthInterface
{
public function login($username, $password)
{
return true;
}
}
class User implements UserInterface
{
public function create(array $data)
{
return true;
}
}
class Mail implements MailInterface
{
public function to($to)
{
return $this;
}
public function subject($subject)
{
return $this;
}
public function send()
{
return true;
}
}
// Create instance of classes
$validate = new Validate();
$user = new User();
$auth = new Auth();
$mail = new Mail();
<?php
interface ValidateInterface
{
public function isValid(array $data);
}
interface AuthInterface
{
public function login($username, $password);
}
interface UserInterface
{
public function create(array $data);
}
interface MailInterface
{
public function to($to);
public function subject($subject);
public function send();
}
<?php
/**
* Facade pattern class
*
* @author altayalp <altayalp@gmail.com>
*/
class SignUpFacade
{
private $validate;
private $user;
private $auth;
private $mail;
public function __construct(ValidateInterface $validate, UserInterface $user, AuthInterface $auth, MailInterface $mail)
{
$this->validate = $validate;
$this->user = $user;
$this->auth = $auth;
$this->mail = $mail;
}
public function signUpUser($userName, $userPass, $userMail)
{
if ($this->validate->isValid(['name' => $userName, 'password' =>$userPass, 'mail' => $userMail])) {
$this->user->create(['name' => $userName, 'password' =>$userPass, 'mail' => $userMail]);
$this->auth->login($userName, $userPass);
$this->mail->to($userMail)->subject('Welcome')->send();
}
}
}
<?php
// Simple sign up process with facade pattern
$facade = new SignUpFacade($validate, $user, $auth, $mail);
$facade->signUpUser($userName, $userPass, $userMail);
<?php
// Simple sign up process without facade pattern
if ($validate->isValid(['name' => $userName, 'password' =>$userPass, 'mail' => $userMail])) {
$user->create(['name' => $userName, 'password' =>$userPass, 'mail' => $userMail]);
$auth->login($userName, $userPass);
$mail->to($userMail)->subject('Welcome')->send();
}
@tibangk01
Copy link

helpful, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment