Home >Backend Development >PHP Tutorial >what is php factory pattern
Factory pattern is our most commonly used instantiation object pattern. It is a pattern that uses factory methods to replace new operations. The famous Jive forum uses the factory pattern extensively. The factory pattern can be seen everywhere in the Java program system. Today we will introduce to you the factory pattern in PHP.
Recommended tutorial: PHP video tutorial
1. What is a factory model?
A class uses its own static method to instantiate a class and return an instance object;
2. What are the characteristics of the factory model?
Class naming characteristics: nameFactory eg: class mysqlFactory{} [This is for standardization, of course, other arbitrary names can also be used]
Static method name: static public function factory($class_name){} [Static method is the interface between the class and the outside world, and returns an object]
3. Advantages?
If the used class changes internally, there is no need to change it everywhere, it only needs to be changed in the class factory class. ,
For example: to connect to the database, you can use mysql, mysqli, pdo, and use different database operation classes according to different parameter configurations
4. Application scenarios
When making a payment interface, it may correspond to different payment gateways in the future: Alipay, Tenpay, online banking, etc.
To facilitate future expansion, it is designed in factory mode. Define a factory that specializes in producing gateway interfaces, abstract it, and make it into an interface form, so that all subclasses must implement its interface. If you add a payment method in the future, which payment method you want to use, just change the parameters.
When registering a user, users are divided into many roles. Such as registered users, anonymous users, administrator users, etc. It can be completely implemented using the idea of factory, the code is also easy to maintain, and operation classes can be generated for each role, etc.
The system connects to multiple different types of databases, mysql, oracle, sqlserver
5. Code examples;
interface mysql{ public function connect(); } class mysqli2 implements mysql{ public function connect(){ echo 'mysqli'; } } class pdo2 implements mysql{ public function connect(){ echo 'pdo'; } } class mysqlFactory{ static public function factory($class_name){ return new $class_name(); } } $obj = mysqlFactory::factory('pdo2'); $obj->connect();
The above is the detailed content of what is php factory pattern. For more information, please follow other related articles on the PHP Chinese website!