Instantly share code, notes, and snippets.

Embed
What would you like to do?
Refactoring to Factory Function in PHP
<?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;
}
}
<?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