PHP bir fabrika sınıfı oluşturmak mümkün mü?

2 Cevap php

Java BeanFactory gibi:

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.

Not: Bu fabrika yöntemi değil

$instance = new FactoryClass();

$instance, dinamik bir sınıf örneği olabilir

2 Cevap

Statik bir yöntem ile kombine __ autoload kullanabilirsiniz. Bu aşırı basitleştirilmiş.

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();

Bu dünyalar crappiest web sitesi var, ama bu ne istediğinizi içeren görünüyor: http://www.devshed.com/c/a/PHP/Design-Patterns-in-PHP-Factory-Method-and-Abstract-Factory/

Kullanım örnekleri için gerçek web sitesine bakınız, ama daha az ya da java fabrikaya benzer.


// 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;
   }
}