repl.it
@jonathanbell/

Class messaging in PHP

PHP CLI

No description

fork
loading
Files
  • main.php
main.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
<?php
 
interface RespondsToUserRegistration 
{

  // All classes that implement this interface, must have a `UserRegisteredFailed()`
  // and a `UserRegisteredSuccessfully` method. This is the contract.

  public function UserRegisteredFailed();

  public function UserRegisteredSuccessfully();

}

class RegisterUser 
{

  // ...

  public function execute(array $data, RespondsToUserRegistration $listener) {
    echo('Registering the user...'.PHP_EOL);
    $listener->UserRegisteredSuccessfully();
  }

  // ...

}

class AuthController implements RespondsToUserRegistration 
{

  protected $registration;

  // This constructor requires an instance of `RegisterUser`, 
  // so we can "message" back to `RegisterUser`’s methods.
  public function __construct(RegisterUser $registration) {
    $this->registration = $registration;
  }

  private function validatePassword($password) {
    if ($password === 'password123') {
      return true;
    }
    return false;
  }

  public function register($username, $password) {
    if (!$this->validatePassword($password)) {
      throw new Exception('Password is no good!');
    }
    // Here we call the `execute()` method on the `RegisterUser` 
    // instance (`$registration`).
    $this->registration->execute([], $this);
  }

  public function UserRegisteredSuccessfully() {
    echo('User created successfully. Now do something else.'.PHP_EOL);
  }

  public function UserRegisteredFailed() {
    echo('User not created successfully. Alert the user.'.PHP_EOL);
  }

}

$registration = new RegisterUser();
$authcontroller = new AuthController($registration);

$authcontroller->register('Philip', 'password123');