-
Notifications
You must be signed in to change notification settings - Fork 2
/
Facade.php
91 lines (76 loc) · 1.93 KB
/
Facade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace DesignPatterns\Structural;
/**
* Facade pattern provides a simplified interface to a complex subsystem (hides the complexity)
*/
class Validator
{
public function isValidMail($userMail)
{
if (!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
}
class User
{
public function create($userName, $userPass, $userMail)
{
// some user registration logic ..
echo "User '{$userName}' was crated..\n";
}
}
class Mail
{
protected $to;
protected $subject;
public function to($mailAddress)
{
$this->to = $mailAddress;
return $this;
}
public function subject($mailSubject)
{
$this->subject = $mailSubject;
return $this;
}
public function send()
{
// sending of mail ..
echo "Email to {$this->to} with subject '{$this->subject}' was sent..\n";
}
}
class SignUpFacade
{
private $validator;
private $userService;
private $mailService;
public function __construct()
{
$this->validator = new Validator();
$this->userService = new User();
$this->mailService = new Mail();
}
/**
* Facade hides the complexity
*/
public function signUpUser($userName, $userPass, $userMail)
{
if (!$this->validator->isValidMail($userMail)) {
throw new \Exception('Invalid email');
}
$this->userService->create($userName, $userPass, $userMail);
$this->mailService->to($userMail)->subject('Welcome')->send();
}
}
# Client code example
// We simple call signUpUser() method and don't care about details of registration process
try {
(new SignUpFacade())->signUpUser('Sergey', '123456', '[email protected]');
} catch (\Exception $e) {
echo "User registration error";
}
/* Output:
User 'Sergey' was crated..
Email to [email protected] with subject 'Welcome' was sent.. */