phpeveryday.com

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


OOP Pattern - Factory: Simple Factory Pattern

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


PHP Factory Pattern Step By Step Tutorial - Part 1: In Object Oriented Programming, we always create new object with new operator. And in some cases, we need call same class for different steps. We can create a factory to avoid always call same class. The factory pattern encapsulates the creation of objects.

This is simple example that we always create new object every function that need it.


<?php
class Vehicle{

  function category($wheel = 0){
  	if($wheel == 2){
		return "Motor";
	}elseif($wheel == 4){
		return "Car";
	}
  }
}

class Spec{
	
  var $wheel = '';
	
  function Spec($wheel){
	$this->wheel = $wheel;	
  }
	
  function name(){
	$wheel = $this->wheel;
  	return Vehicle::category($wheel);
  }

  function brand(){
	$wheel = $this->wheel;  
  	$kind =& Vehicle::category($wheel);
	if($kind == "Motor"){
		return array('Harley','Honda');
	}elseif($kind = "Car"){
		return array('Nisan','Opel');	
	} 
  }
	
}

$kind = new Spec(2);
echo "Kind: ".$kind->name();
echo "<br>";
echo "Brand: ".implode(",",$kind->brand());
?>

This picture show how to implement factory pattern:

PHP Factory Pattern

This is complete code after changing (implement factory pattern)


<?php
class Vehicle{

  function category($wheel = 0){
  	if($wheel == 2){
		return "Motor";
	}elseif($wheel == 4){
		return "Car";
	}
  }
}

class Spec{
	
  var $wheel = '';
  var $vc    = '';
  	
  function Spec($wheel){
	$this->wheel = $wheel;
	$this->_getVehicle();
  }
  
  function &_getVehicle(){
	$wheel = $this->wheel;
  	$this->vc =& Vehicle::category($wheel);
  }
	
  function name(){
  	return $this->vc;
  }

  function brand(){
	if($this->vc == "Motor"){
		return array('Harley','Honda');
	}elseif($this->vc = "Car"){
		return array('Nisan','Opel');	
	} 
  }
	
}

$kind = new Spec(2);
echo "Kind: ".$kind->name();
echo "<br>";
echo "Brand: ".implode(",",$kind->brand());
?>
In this practice, we create a factory within the object itself.


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
CAPTCHA - part 3 : "Are you human or ....?" (Build Your CAPTCHA)

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


615
posting