views:

62

answers:

2

Like the BeanFactory in java:

In the much more common case where the BeanFactory itself directly creates the bean by calling its constructor (equivalent to Java code calling new), the class attribute specifies the class of the bean to be constructed. In the less common case where the BeanFactory calls a static, so-called factory method on a class to create the bean, the class attribute specifies the actual class containing the static factory method.

Note:it's not the factory method

$instance = new FactoryClass();

The $instance may be any class instance dynamically

A: 

It's the worlds crappiest website, but this seems to contain what you want: http://www.devshed.com/c/a/PHP/Design-Patterns-in-PHP-Factory-Method-and-Abstract-Factory/

See the actual website for usage examples, but more or less similar to the java factory.


// define abstract 'ArrayFactory' class
abstract class ArrayFactory{
   abstract public function createArrayObj($type); 
}

// define concrete factory to create numerically-indexed array
objects
class NumericArrayFactory extends ArrayFactory{
   private $context='numeric';
   public function createArrayObj($type){
     $arrayObj=NULL;
     switch($type){
       case "uppercase";
         $arrayObj=new UppercasedNumericArrayObj();
         break;
       case "lowercase";
         $arrayObj=new LowercasedNumericArrayObj();
         break;
       default:
         $arrayObj=new LowercasedNumericArrayObj();
         break; 
     }
     return $arrayObj;
   }
}

// define concrete factory to create associative array objects
class AssociativeArrayFactory extends ArrayFactory{
   private $context='associative';
   public function createArrayObj($type){
     $arrayObj=NULL;
     switch($type){
       case "uppercase";
         $arrayObj=new UppercasedAssociativeArrayObj();
         break;
       case "lowercase";
         $arrayObj=new LowercasedAssociativeArrayObj();
         break;
       default:
         $arrayObj=new LowercasedAssociativeArrayObj();
         break; 
     }
     return $arrayObj;
   }
}
corprew
Seems too complicated,is there a simplified version?
+1  A: 

You can use __autoload combined with a static method. This is overly simplified.

MyObject.php:

<?php
class MyObject
{
    public static function Create()
    {
        return new MyObject();
    }

    public function hello()
    {
        print('hello!!!');
    }
}

index.php

<?php
function __autoload($className)
{
    require_once($className . '.php');
}

$o = MyObject::Create();
$o->hello();
Michael Dean