Common PHP factory design patterns, php Factory Design Patterns
I. Factory Model
Is a type that has some methods for creating objects for you. You can use the factory class to create objects instead of using new directly. In this way, if you want to change the type of the created object, you only need to change the factory. All codes used in the factory are automatically changed.
The following code shows an indication column of the factory class. The server side of the equation consists of a database and a set of PHP pages that allow you to add feedback, request feedback lists, and obtain articles related to specific feedback.
The IUser interface defines what operations a user object should perform:
interface IUser{ function getName();}
The implementation of IUser is called User:
class User implements IUser{ public function __construct( $id ) { } public function getName() { return "Jack"; }}
The UserFactory class creates an IUser object:
class UserFactory{ public static function Create( $id ) { return new User( $id ); }}
The test code will request the factoryUser
Object and OutputgetName
Result of the method:
$pr = UserFactory::Create( 1 );echo( $pr->getName()."\n" );
There is a variation in the factory model that uses the factory method. Class. This method is useful when you create an object of this type. For example, suppose you need to create an object first and then set many attributes. The factory mode of this version encapsulates the process in a single location, so that you do not need to copy complicated initialization code or paste the copied code everywhere in the code base.
Interface IUser // interface {function getName ();} class User implements IUser {public static function Load ($ id) // static function {return new User ($ id );} public static function Create () // static function {return new User (null);} public function _ construct ($ id) {}// constructor public function getName () {return "Jack" ;}}$ uo = User: Load (1); echo ($ uo-> getName (). "\ n ");