phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


OOP Pattern - Factory: Saving Energy for Repeating Steps

Tag: oop, pattern, factory pattern   Category: PHP Classes
post: 18 Feb 2008 read: 462


PHP Factory Pattern Step By Step Tutorial - Part 3: This post show us how to avoid copy and paste job by implement factory pattern. You don't need rewrite same code for same job. It will look your code more clear.

<?
class Bidding{
  var $lowest  = 0;
  var $highest = 0;
  var $yourbid = 0;

  function Bidding($yourbid){
  	$yourbid = (int)$yourbid;
	if($yourbid <= 0){
	  trigger_error("price must be greater than 0");
	}  
	$this->yourbid = $yourbid;	
  }

  function bidRange($lowest = 0, $highest = 0){
  	$lowest = (int)$lowest;
	if($lowest <= 0){
	  trigger_error("price must be greater than 0");
	}
	$this->lowest = $lowest;		
	
  	$highest = (int)$highest;
	if($highest <= 0){
	  trigger_error("price must be greater than 0");
	}				
	$this->highest = $highest;		
		
  }
  
  function checkBid(){
  	if($this->yourbid < $this->lowest 
	   || $this->yourbid > $this->highest){
		return "You are not in range!";
	}else{
		return "Your bid is accepted!";
	}
  }
    
}

$bid = new Bidding(100);
$bid->bidRange(100,1000);
echo $bid->checkBid();

?>

Following picture will show us how to improve above code with factory pattern:

php factory pattern



<?
class Bidding{
  var $lowest  = 0;
  var $highest = 0;
  var $yourbid = 0;

  function Bidding($yourbid){
	$this->yourbid = $this->checkPrice($yourbid);
  }
  
  function checkPrice($price){
  	$price = (int)$price;
	if($price <= 0){
	  trigger_error("price must be greater than 0");
	}else{
	  return $price;
	}
  }

  function bidRange($lowest = 0, $highest = 0){
  	$this->lowest = $this->checkPrice($lowest);
  	$this->highest = $this->checkPrice($highest);		
  }
  
  function checkBid(){
  	if($this->yourbid < $this->lowest 
	   || $this->yourbid > $this->highest){
		return "You are not in range!";
	}else{
		return "Your bid is accepted!";
	}
  }
    
}

$bid = new Bidding(100);
$bid->bidRange(100,1000);
echo $bid->checkBid();

?>


Series this article:
OOP Pattern - Factory: Simple Factory Pattern
OOP Pattern - Factory: External Factory Class
OOP Pattern - Factory: Saving Energy for Repeating Steps

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting