search
HomeBackend DevelopmentPHP ProblemHow to build your own web framework with PHP?

This article will give you one minute to learn how to use PHP to build your own web framework? (Sharing) has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to build your own web framework with PHP?

The WEB mentioned here refers to the PHP WEB program running under apache.

We must first understand the operating mechanism of PHP under apache and the life cycle of requests.

PHP is a scripting language. Its execution process starts from the file entry to the end of the file. It can contain or reference other files and is process-oriented. In the process, objects can be used to implement various required logical processing. You can use one or more objects to complete the required functions, and you can also tell an object what function you want to complete. This is an object-oriented development method and a common development method. Therefore, in the process-oriented operating mechanism, use the object-oriented development method.

The life cycle of each HTTP request also starts from the entrance until the end of the program. The variables in it will no longer exist. The variables of different HTTP requests are independent and do not affect each other. We can use global declarations, $GLOBALS global array variables, and static static variables to share data in the same HTTP request; use session to achieve session-level sharing; use cache to achieve site-wide data sharing. The global statement is generally used in methods and is used in process-oriented development. It is not usually used. $GLOBALS and static are often used, but they cannot be operated directly. Instead, they are managed in objects or special methods. For example, the commonly used singleton mode is saved using $GLOBALS and static.

In PHP programs, we will consider making the framework as simple, efficient, clear, and easy to use as possible, which is good for development and maintenance.

The basic program model uses the MVC model, which is layered and divided into modules. At the same time, a useful URL router is required to cooperate with MVC.

URL router: A very critical component that determines the organizational structure of the source code file and the clarity of the code. A good router can easily find the logical entry, reflecting the ease of use of the framework.​

​ Model: Always use arrays. The main concern when using arrays is that the content of the array is unclear. In the project, the attributes refer to database fields, so the content of the array is relatively clear. Model operations are encapsulated using the data access layer DAO. In database access, it is also more efficient to convert directly into array form. For interactive data objects of other systems, there are generally interface document definitions. Regarding the Active Record technology in ORM, it is better not to use it or not.

View: I started using smarty, but in the performance report, the method executed by smarty took too much time. Later, I used tmd_tpl, which is just one file, easy to use and efficient. Easy to modify. In the view template, combine PHP syntax and supplement it with template variables. The idea of ​​MVC is separation, which does not mean that PHP syntax cannot be used in View. If it is an API interface, the data can be directly converted into a specific format result and returned.

Controller: or action represents a behavior, a method, and an interface. Only one layer of controller is often not enough. It is generally divided into an interface layer, a business layer, a data access layer, and a communication layer. The interface is responsible for parameter verification, access permission control, calling specific services, and finally returning data or displaying pages, etc. It is best for all businesses to start with the interface layer. Before that, we should only do framework things. When we need to read a certain business implementation, we only need to start reading along the interface layer entrance. The business layer performs actual business functions. The business layer obtains data from the data access layer and performs business processing. The data access layer obtains data from the database or calling interface and can perform simple data conversion processing. If PHP is only used as the front end for data display, and the back end is executed by C/C/GO, etc., then you only need to encapsulate the business layer, request the data to the back end in the business layer, and then return it to the interface layer.

The above is the basic framework structure of the program, or the process structure of the business, which is usually the most important part of the system. But it is still far from being practical, and there are still many basic functions to be added, such as session processing, database access, log processing and other functions. These basic functions are generally independent of the framework and can be applied on different frameworks. Functional classes should not be too tightly coupled to the framework, and generally use combination methods. We encapsulate these basic functions into core classes in a way that is easy to use, and use single or multiple instances to call them, or further encapsulate the classes into global methods for easy use.


## As shown in the picture above, if the center is well grasped and organized, it reflects the business capabilities, because with the development of the business, a business layered structure will naturally be formed; The good integration of peripherals reflects the capabilities of the framework and how to use/develop it comfortably and smoothly.

When calling functional classes or business classes, class loading or import issues will be involved. How about using the autoloading function? Based on personal experience and IDE support, I think it is unintuitive and unfriendly to IDE. For example, F3 cannot find a defined method. This is our experience when learning open source systems, and it also has an impact on performance. It is more convenient to require/include directly. Although it requires writing more code, it does bring great convenience to development, maintenance and reading (except that it is inconvenient to change the reference after modifying the name, but it can be modified through global search). Some public classes are referenced globally in the entry, and business classes are referenced on demand. Performance loss? Because the business is vertical most of the time, generally require/include can be used instead of require_once/include_once. It doesn't matter even if you use a few more onces. First of all, the correctness can be guaranteed, and the overall performance of the program is not determined by this. Automatic loading will add a lot of judgments, instructions and stack operations, and file search and loss of performance will probably be more. However, a good automatic loading implementation can still be considered. Business files can be considered. Framework files do not use automatic loading, and they must be simple, accurately positioned, efficient, and avoid duplication.

How to use it after loading? Method, class object method or class static method call? Depends on different scenarios. Global functions are generally method calls, such as thinkPHP's C method for obtaining configuration content, which is called directly. If in the layer, interface layer->business layer->data access layer, use class static method call. Some global functional operations, such as database operation classes, some third-party functional classes, and polymorphic functional classes, are generally used using singletons without the need to generate new objects multiple times.

About reflection functions, annotations, IOC, aspect-oriented programming and other functions and practices that are very useful in other languages, they can basically be implemented in PHP. Although I have seen many practical examples, I have not considered applying them. In the project, being able to implement it does not mean that it must be used. LAMP can easily develop a website, and generally it is a website application, which is different from a framework (such as spring). Therefore, the use of PHP is more focused on the business process and performance of the website, making the business process clear. Ease of maintenance ensures flexibility without complicating business or compromising performance. High-performance websites need to be short, flat and fast, not to mention that many websites use PHP for front-end rendering and c/c/java for back-end business, so PHP websites should be as simple as possible. Because we are a business website system, the business process is determined, and the execution is from beginning to end. The business code reflected in the code must be clear. If it is reflected or injected during the execution process, it will affect People's understanding of the business may also ignore what the framework has done when developing and maintaining bug location. Unlike some general frameworks or third-party packages, which need to be flexible enough to be called, flexibility is complicated and a certain amount of performance has to be sacrificed. To use these functions, you often need to do some initialization code or some configuration initialization in advance, and each HTTP request must be executed once. Even for simple functions, it is not necessary, unlike Java which only initializes once. For example, some restfull frameworks will define routes at the entrance, as well as a large number of configurations. Although this has a certain degree of clarity and flexibility, in this case it is recommended to use the idea of ​​​​convention over configuration.

Some of the above practices are somewhat unusual or extreme, but they have also gone through the process of original --> framework (advanced features, techniques) --> returning to the original, which can be understood as personal unique feelings or experience. Using the basic features of PHP makes it easy to start a project, understand business processes, and develop and maintain it. There is no excessive loss in performance, and it can also facilitate positioning optimization. In short, primitive simplicity is the best improvement in performance; writing the business in vertical isolation and seeing what has been done at a glance improves development efficiency.

If you do not have the ability to develop your own PHP framework according to project requirements at the beginning, then after using a framework for the first time, you should consider implementing your own website on demand in other projects and forming your own framework.

I think the simplest and easiest to use PHP website framework requires a route, a controller and a view template engine. Other functional modules can be added as needed.

Recommended study: "PHP Video Tutorial"

The above is the detailed content of How to build your own web framework with PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools