This repository has been archived by the owner on Oct 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
v5.php
98 lines (83 loc) · 2.13 KB
/
v5.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
92
93
94
95
96
97
98
<?php
class App
{
protected $auth = null;
protected $session = null;
public function __construct(Auth $auth, Session $session)
{
$this->auth = $auth;
$this->session = $session;
}
public function login($username, $password)
{
if ($this->auth->check($username, $password)) {
$this->session->set('username', $username);
return true;
}
return false;
}
}
interface Auth
{
public function check($username, $password);
}
class DbAuth implements Auth
{
public function __construct($dsn, $user, $pass)
{
echo "Connecting to '$dsn' with '$user'/'$pass'...\n";
sleep(1);
}
public function check($username, $password)
{
echo "Checking username, password from database...\n";
sleep(1);
return true;
}
}
class HttpAuth implements Auth
{
public function check($username, $password)
{
echo "Checking username, password from HTTP Authentication...\n";
sleep(1);
return true;
}
}
class Container
{
protected static $map = [];
public static function register($name, $class, $args = null)
{
static::$map[$name] = [$class, $args];
}
public static function get($name)
{
list($class, $args) = isset(static::$map[$name]) ?
static::$map[$name] :
[$name, null];
if (class_exists($class, true)) {
$reflectionClass = new ReflectionClass($class);
return !empty($args) ?
$reflectionClass->newInstanceArgs($args) :
new $class();
}
return null;
}
}
class Session
{
public function set($name, $value)
{
echo "Set session variable '$name' to '$value'.\n";
}
}
Container::register('Auth', 'DbAuth', ['mysql://localhost', 'root', '123456']);
Container::register('Auth', 'HttpAuth');
$auth = Container::get('Auth');
$session = Container::get('Session');
$app = new App($auth, $session);
$username = 'jaceju';
if ($app->login($username, 'password')) {
echo "$username just signed in.\n";
}