PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS

seen various examples of polymorphism in which the client understands a component’s interface but
the actual component may vary at runtime.
In some circumstances, you may wish to drive an even greater wedge between components than
this. Consider a class responsible for handling a user’s access to a system:


class Login {
const LOGIN_USER_UNKNOWN = 1;
const LOGIN_WRONG_PASS = 2;
const LOGIN_ACCESS = 3;
private $status = array();


function handleLogin( $user, $pass, $ip ) {
switch ( rand(1,3) ) {
case 1:
$this->setStatus( self::LOGIN_ACCESS, $user, $ip );
$ret = true;
break;
case 2:
$this->setStatus( self::LOGIN_WRONG_PASS, $user, $ip );
$ret = false;
break;
case 3:
$this->setStatus( self::LOGIN_USER_UNKNOWN, $user, $ip );
$ret = false;
break;
}
return $ret;
}


private function setStatus( $status, $user, $ip ) {
$this->status = array( $status, $user, $ip );
}


function getStatus() {
return $this->status;
}


}


In a real-world example, of course, the handleLogin() method would validate the user against a
storage mechanism. As it is, this class fakes the login process using the rand() function. There are three
potential outcomes of a call to handleLogin(). The status flag may be set to LOGIN_ACCESS,
LOGIN_WRONG_PASS, or LOGIN_USER_UNKNOWN.
Because the Login class is a gateway guarding the treasures of your business team, it may excite
much interest during development and in the months beyond. Marketing might call you up and ask that
you keep a log of IP addresses. You can add a call to your system’s Logger class:


function handleLogin( $user, $pass, $ip ) {
switch ( rand(1,3) ) {
case 1:
$this->setStatus( self::LOGIN_ACCESS, $user, $ip );
$ret = true;
break;
case 2:

Free download pdf