Home Backend Development PHP Tutorial PHP design pattern summary-factory pattern

PHP design pattern summary-factory pattern

Dec 17, 2016 am 10:35 AM

What is the purpose or goal of using factory pattern?

The biggest advantage of the factory pattern is in creating objects, which is to encapsulate the process of creating objects, so that a new object can be generated at any time.
Reduce the code and copy and paste, the coupling relationship is heavy, and it affects other parts of the code.

In layman’s terms, you used to use new to create an object, but now this process is encapsulated.
Assuming that the factory mode is not used: then class a is called in many places, and the code will create an instance like this: new a(). Suppose that one day the name of class a needs to be modified, which means that many calling codes must be modified.

The advantage of the factory pattern lies in creating objects.
The advantage of the factory pattern lies in creating objects. Establish a factory (a function or a class method) to create new objects. Its task is to encapsulate the object creation process.
Creating objects does not use new. Instead, define a method for creating object instances.

Each class may need to connect to the database. Then encapsulate the connection to the database in a class. In the future, use the class name in other classes:

Why introduce abstract concepts?
Think about it, in real life, when we are unable to determine something specific, we often classify a category of things into an abstract category.
Factory method:
For example, if your factory is called "Cigarette Factory", then there can be "Septwolves Factory", "China Factory", etc. However, this factory only produces one product: cigarettes;
Abstract Factory: It is impossible to describe what it produces. What product, it produces many types of products (so the abstract factory will generate sub-factories).
Your factory is comprehensive and produces "a series" of products instead of "one", for example: producing "cigarettes" and "beer", etc. Then it can also have specific factories derived from it, but these factories all produce this series of products, but the taste may be different because of different regions and to adapt to local tastes.
Factory pattern: understood as a factory that only generates one product. For example, those who produce cigarettes.
Factory method: a product production line in a factory. For example, the keyboard generation process.

Others will refute: I have nothing to do when I am full, so I must change the class name? Maybe. Generally, class names are not modified.

In fact, there are many variations of the factory pattern, and grasping the essence is the key: as long as different class instances can be generated based on different parameters, then it is consistent with the design idea of ​​the factory pattern.

This reminds me that there are often methods in the framework that are responsible for generating specific class instances for calling.

Since I have used phpcms before, it is better to use phpcms to help understand, as follows:

pc_base:load_app_class("order"');//The parameter name is the class name. An instance of order will be generated. Passing different parameters to get different class instances is consistent with the factory pattern.
pc_base:load_app_class("comment"');//Generate a comment class instance

//Of course, the load_app_class method also incorporates the idea of ​​the singleton mode. Avoid calling n times and repeatedly creating n identical instances


A typical application that I think of in factory mode is: PHP may need to link to mysql, or it may need to link to sqlserver, or other databases. Then make an abstract database class.

This class is a factory class that is responsible for generating different objects.

It is very convenient to expand in this way. When we directly connect to the database, instead of using the code new Mysql ($host, $username, $password, $dbname), we can dynamically generate an instance to connect to the database. It can be mysql or connected to oracle. ​​​​') {


$classname = 'Driver_' . $db_class_name;
                                                                                                        .



}



DbFactory::factory("mysql");

DbFactory::factory("oracle");


There is also a corresponding implementation in the thinkphp framework:

Db.class.php is a factory class (can also be called The database middle layer is called the middle layer because it can operate various databases such as MySQL and Oracle. This class is the middle layer, which allows programmers to connect without changing the original query code. Mysql, oracle and other databases.

Db.class.php has a factory() method to create different database instances

public function factory($db_config='') {
                                                                                                                                                                                               Read the database configuration         $db_config = $this->parseConfig($db_config); L('_NO_DB_CONFIG_'));
                                       ’’’’’’’ ​​​$path = EXTEND_PATH ;
} 检 // Check the driver
if (require_cache ($ Path.'driver/db/<. class. class.php> $ db = new $ class ($ db_config);
// / Get the current database type
                                                                                                                                                   $db-> ;dbType = $this->_getDsnType($db_config['dsn']);
                                                                                                                                       throw_exception(L('_NOT_SUPPORT_DB_ ').': ' . $db_config['dbms']);
                                                                               return $db; 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.


The book (English name is PHP 5 Power Programming) also mentioned an example of factory mode. I learned a trick: when registering users, divide them into users with many roles. Such as registered users, anonymous users, administrator users, etc. Complete use can be achieved using the idea of ​​​​factories, the code is also easy to maintain, and operation classes can be generated for each role.

Define the following classes:

UserFactory user factory class, responsible for generating different user classes
User: the base class of user classes, all user classes inherit this class
Classes with different roles: registered user classes, anonymous users Class, administrator user class







For more PHP design pattern summary-factory pattern related articles, please pay attention to PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles