Example #1
0
 public function generateCall(FactoryMethod $method)
 {
     $code = '';
     if ($method->acceptsVariableArguments()) {
         $code .= $this->indent . self::INDENT . '$args = func_get_args();' . PHP_EOL;
     }
     $code .= $this->indent . self::INDENT . 'return ';
     if ($method->acceptsVariableArguments()) {
         $code .= 'call_user_func_array(array(\'' . '\\' . $method->getClassName() . '\', \'' . $method->getName() . '\'), $args);' . PHP_EOL;
     } else {
         $code .= '\\' . $method->getClassName() . '::' . $method->getName() . '(' . $method->getParameterInvocations() . ');' . PHP_EOL;
     }
     return $code;
 }
}
class Print_Triangle extends Print_Shape
{
    public function __construct()
    {
        $this->shape = "triangle";
    }
    public function get_shape()
    {
        return $this->shape;
    }
}
class FactoryMethod
{
    public static function build($type)
    {
        $classname = 'Print_' . $type;
        if (!class_exists($classname) and !(include_once 'Classes/' . $type . '.php')) {
            throw new Exception('Missing class.');
        } else {
            return new $classname();
        }
    }
}
$test1 = FactoryMethod::build("rectangle");
$test2 = FactoryMethod::build("square");
$test3 = FactoryMethod::build("triangle");
printf("I'm a %s <br>", $test1->get_shape());
printf("I'm a %s <br>", $test2->get_shape());
printf("I'm a %s <br>", $test3->get_shape());
echo "Factory Method pattern works fine";
Example #3
0
 public function generateImport(FactoryMethod $method)
 {
     return $this->indent . self::INDENT . "require_once '" . $method->getClass()->getFile() . "';" . PHP_EOL;
 }