Understand PHP's Factory mode factory pattern

Source: Internet
Author: User
The factory class is a class that is designed to create other objects, and factory classes are very important in the practice of polymorphism programming. It allows you to dynamically replace classes, modify configurations, and make your application more flexible. Mastering the factory model is essential for web development.

Factory mode is typically used to return different classes of similar interfaces, and a common use of factories is to create polymorphic providers.

Usually the factory pattern has a key construct, the static method that is generally named factory. This static method can accept any number of arguments and must return an object.

Program List: Basic Factory class

<?php
Class Fruit {
Object returned from the factory class
}

Class Fruitfactory {

public static function factory () {
Returns a new instance of an object
return new Fruit ();
}
}

Call Factory
$instance = Fruitfactory::factory ();
?>

Program List: Using factory class production objects

<?php
Class Example
{
The Parameterized factory method
public static function factory ($type)
{
if (include_once ' drivers/'. $type. '. php ') {
$classname = ' Driver_ '. $type;
return new $classname;
} else {
throw new Exception (' Driver not found ');
}
}
}
Load a MySQL Driver
$mysql = example::factory (' mysql ');
Load an SQLite Driver
$sqlite = example::factory (' SQLite ');
?>

Program List: A complete factory class

The following program defines a generic factory class that produces an empty object that can hold all of your operations, and you can get an instance of the operation that is in that instance.

<?php

/**
* Generic Factory class
*
* This Magic Factory would remember all operations you perform on it,
* and apply them to the object it instantiates.
*
*/
Class Fruitfactory {
Private $history, $class, $constructor _args;

/**
* Create a factory of given class. Accepts extra arguments to being passed to
* Class constructor.
*/
function __construct ($class) {
$args = Func_get_args ();
$this->class = $class;
$this->constructor_args = Array_slice ($args, 1);
}

function __call ($method, $args) {
$this->history[] = Array (
' Action ' = ' call ',
' Method ' = $method,
' Args ' = $args
);
}

function __set ($property, $value) {
$this->history[] = Array (
' Action ' = ' Set ',
' Property ' = $property,
' Value ' = $value
);
}

/**
* Creates an instance and performs all operations that were do on this magicfactory
*/
function instance () {
# Use Reflection to create a new instance, using the $args
$reflection _object = new Reflectionclass ($this->class);
$object = $reflection _object->newinstanceargs ($this->constructor_args);

# alternative method that doesn ' t use Reflectionclass, but doesn ' t support variable
# Number of constructor parameters.
$object = new $this->class ();

# Repeat all remembered operations, apply to new object.
foreach ($this->history as $item) {
if ($item [' action '] = = ' call ') {
Call_user_func_array (Array ($object, $item [' method ']), $item [' args '];
}
if ($item [' action '] = = ' Set ') {
$object->{$item [' property ']} = $item [' value '];
}
}

# done
return $object;
}
}

Class Fruit {
Private $name, $color;
Public $price;

function __construct ($name, $color) {
$this->name = $name;
$this->color = $color;
}

function SetName ($name) {
$this->name = $name;
}

function introduce () {
Print "Hello, this is an {$this->name} {$this->sirname}, it price is {$this->price} RMB.";
}
}

# Setup a factory
$fruit _factory = new Fruitfactory (' Fruit ', ' Apple ', ' gonn ');
$fruit _factory->setname (' Apple ');
$fruit _factory->price = 2;

# Get An instance
$apple = $fruit _factory->instance ();
$apple->introduce ();
?>

Program Run Result:

Hello, this was an Apple, it price is 2 RMB.

The factory model provides a transition interface for creating objects to isolate the concrete process masks for creating objects to achieve greater flexibility.

The factory model can be divided into three categories:

Simple Factory mode (Factory)

Factory mode (Factory method)

Abstract Factory mode (Factory)

These three modes are progressively abstracted from top to bottom and more general.

The simple factory model is also called the Static factory method mode. Renaming can tell that this pattern must be simple. The purpose of its existence is simple: Define an interface for creating objects. The factory method pattern removes the static property of the factory method in the simple Factory mode, allowing it to inherit from the quilt class. The pressure to concentrate on factory methods in a simple factory model can be shared by different factory subclasses in the factory method model.

The factory method pattern seems to have been perfectly wrapped in the creation of objects, allowing the client to process only the interfaces provided by the abstract product role. Do we have to be in the code all over the factory? It doesn't have to be big. Perhaps you might consider using the factory method mode under the following conditions:

When the client program does not need to know the creation process to use the object.

The object used by the client is subject to change, or there is no knowing which specific object to use.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.