Created
March 30, 2016 08:53
-
-
Save matthewjackowski/a81a69034102ab06ac9c0065233dbf84 to your computer and use it in GitHub Desktop.
Refactoring to Factory Function in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Message object class used to control when messages are output | |
* @package Brilliantcoding | |
*/ | |
/** | |
* Message Class | |
*/ | |
class Message { | |
private $sendTime; | |
private $text; | |
/** | |
* Public constructor, sets class vars | |
* @param string $text The message to send | |
* @param time $scheduleTime Exact time to schedule message | |
* @param time waitDuration Time from now to send message | |
*/ | |
public function __construct( $text, $scheduleTime, $waitDuration ) { | |
if ( $scheduleTime ) { | |
$this->sendTime = $scheduleTime; | |
} else if ( $waitDuration ) { | |
$this->sendTime = time() + $waitDuration; | |
} else { | |
$this->sendTime = time(); | |
} | |
$this->text = $text; | |
} | |
/** | |
* Public send function, only sends if the sendTime has passed | |
* | |
* @return boolean, returns true if the message was sent | |
*/ | |
public function send() { | |
$is_sent = False; | |
if ( $this->sendTime < time() ) { | |
echo $this->text; | |
$is_sent = True; | |
} | |
return $is_sent; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include 'Message.php'; | |
class MessageFactory { | |
static function immediateMessage( $text ) { | |
return new Message( $text, false, false ); | |
} | |
static function scheduledMessage( $text, $time ) { | |
return new Message( $text, $time, false ); | |
} | |
static function delayedMessage( $text, $duration ) { | |
return new Message( $text, false, $duration ); | |
} | |
} | |
$msg1 = MessageFactory::immediateMessage( 'say anything' ); | |
$status = $msg1->send(); | |
$msg2 = MessageFactory::scheduledMessage( 'say anything later', '2012-05-21 22:02:00' ); | |
$status = $msg2->send(); | |
$msg3 = MessageFactory::delayedMessage( 'wait a bit to say anything', 20 ); | |
$status = $msg3->send(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment