Home Tutorial Php Phpoop PHP Factory Method

 
 

Share on Google+Share on Google+
PHP Factory Method
Posted on: February 23, 2010 at 12:00 AM
Advertisement
It is very common problem that sometimes we need to change a little in our coding and subsequently we have to change so many places like in other class, function etc. It is called tight coupling. In this case factory pattern helps us a lot. In the current tutorial we will study about factory method and how to implement this in PHP.

PHP Factory Method:

It is very common problem that sometimes we need to change a little in our coding and subsequently we have to change so many places like in other class, function etc. It is called tight coupling.

In bigger projects/programs a big section of coding is heavily depend on a class or a function. Like if we would like to change the data provider, suppose from XML file to database or vice versa or any other kind of file then we have to change lots of coding.

In this case factory pattern helps us a lot. The factory method is a class which is used to create objects. Using this class we can create object without using new operator. In this way if we want change the type of the object, all we need to do is change the factory. 

It is advisable that we should always use factory methods instead of constructors because it has following benefits over it:

  1. Every factory method name should be different
  2. We can create objects of same class type as well as of derived class type.
  3. Unlike constructors factory methods need not to create or initialize the methods all the time.
  4. Factory methods can be virtual but constructors can not be virtual.
  5. Factory methods can select to create objects of different types.

PHP Factory Method Example:

<?php

interface student{

function getName();}

class stuPersonal implements student{

public function getName(){

return "rose";}

public function __construct($roll){}

}

class studentFactory{

public static function create($roll){

return new stuPersonal($roll);}

}

$stu=studentFactory::create(1);

echo $stu->getName();

?>

 

Output:

rose

 

Advertisement

Related Tags for PHP Factory Method:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 23, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com