Home php教程 PHP开发 Rethinking PHP programming methods (Part 1)

Rethinking PHP programming methods (Part 1)

Dec 21, 2016 am 10:50 AM

A few years ago, PHP5 changed from a process-oriented language to an object-oriented language, which caused a huge stir in various technical forums. Many people asserted that PHP would destroy itself, but soon after the dust settled, most people switched from not supporting PHP to supporting it. It has also transformed from being jokingly called a children's toy in the 4.0 era to becoming the third largest language after Java and C. Being involved in the whole debate, I thought I had a complete understanding of object-oriented, and gradually began to fully adopt object-oriented programming. After 2008, I even started writing programs only under the zend framework.

But the work experience in recent months has made me reflect, and I began to rethink the most famous question of the year: "If it is really completely object-oriented, why don't we use JAVA directly? Why do we need two JAVA?" Yes , One of the reasons for using PHP is that we do not necessarily have to be object-oriented. All programming technologies and programming concepts are just means. Meeting customer needs in the shortest time is our goal. It is undoubtedly wrong to talk about any technology without this goal. A very typical example is the open source forum In the program, everyone in PHPER respects PHPBB, but scorns the technical content of DISUCZ's code. However, when it comes to actually building a forum, which of us uses PHPBB? Most of the forums in China are owned by DISCUZ. In the past two years or so, I have been stuck on object-oriented and wasted a lot of time. This is a serious mistake I made.

So, I decided to reorganize my understanding of PHP programming. In the future, when selecting projects, I can choose a more appropriate architecture instead of just following technology. Welcome everyone to make bricks.

1. The role of functions

To this day, any friend who is not a computer major should have learned a computer language. In China, it is usually basic. If you are lucky, it may also be C, branch statements and Loop statements are a compulsory part of it, and if you don't learn functions well, you will probably be careless and pass. Even if there is no such thing as a function in the world, the program can still complete all functions (what a pity, I have just seen such a project in the past few months).

So, what do we need functions for? Countless textbooks tell us that it is for reusability. Yes, after a function is written, if you use the same function next time, you can just call it directly without having to write it again. This is the original intention and basic function of function invention. However, if we expect a function to be less commonly used, should we not use the function? No, even if we adopt process-oriented programming, we still need to use functions as much as possible, subdivide the functions as much as possible, and write an independent function for each function. Using functional programming has the following obvious advantages:

Clear logic. No matter how complex a function is, when it is subdivided and subdivided into multiple single functions, the logic of each single function is very simple. We can easily fill in the code according to the logic without having to worry about it. ;

Easy to test. Writing a program using functions actually creates a natural interruption for the program. We can quickly know which piece of code has an error. Every programmer should know that the time we spend testing code is usually twice or even three times the time we spend writing code.

Easy to read. After a program has been written for a period of time, customers find problems when using it, or need to change functions. Programmers may not be able to remember clearly even the code they wrote themselves, and when reading a program mainly written by functions , the main program is basically an outline, and we can quickly find the corresponding functions along the main program's context.

Easy to reuse. Usually, a function must have been tested when it is completed. As long as the test is more careful at the time, you can assume that the function is correct in the future. You can call it according to the function description at any time without paying attention to the details.

Quick modification. Sometimes we cannot avoid some functional modifications. When you call the same functional function in multiple programs, as long as you modify this function, everything will change at the same time, and you no longer need to modify it one by one.

Because of the above advantages, using functions for process-oriented programming is a method recognized by everyone. I have never seen anyone questioning it in any forum.

2. Code comments

Different from the habits of many people, I like a lot of comments, and they are comments that comply with the phpdocument standard. In this way, when I or my colleagues use professional editors such as zend studio or netbeans When the code is opened in the browser, if you enter the first letter, the functions and methods I wrote will automatically pop up, and then you can see the function functions, usage, parameter requirements and return format I commented in Chinese. Every programmer hopes to have as many code comments as possible, but many people rarely write comments. I learned some comments in forums and QQ groups, and found that this is probably not caused by laziness. They don’t write comments or rarely write comments. Writing notes is more due to the fear of unemployment and lack of basic self-confidence, so that it is expected that it will be difficult for others to take over to ensure the stability of one's position.

3. Replace functions with classes

Finally let’s talk about the basic methods of object-oriented programming. In classes, we call variables attributes and functions called methods. Every time foreigners come up with a new concept, they always like to do some new naming. The advantage of this is , when we mentioned properties and methods, we always seemed more knowledgeable than those who talked about variables and functions. Of course, in essence, they are exactly the same thing.

Why use classes? According to my personal understanding, initially, this is mostly due to the scope of variables. The security of global variables has been mentioned in the introductory tutorial of C language. Not only is it easy to create loopholes and be hacked, but more often, when you write your own code, you will also have various expectations because of the same name of the global variable. No trouble. If you pass each variable with parameters, it will be cumbersome. Thanks to a great programming tool like Netbeans, I actually don't have to enter these variables manually, I just look at them in displeasure. Obviously it is a variable used by most functions or at least a group of functions, but it always feels uncomfortable to have to pass values ​​repeatedly. So, there are classes, and, after PHP5.0, the scope of attributes (variables) and methods (functions) can be defined in detail in the class.

At the same time, another basic benefit of using classes is that you can group functions. When there are enough functions, it will be difficult to find them. Separate the functions by class. Those methods that are only called by other functions and do not need to be called directly by users can simply be made private to prevent colleagues from accidentally calling them. In this way, a The public function library is completely decomposed into multiple classes.

Many times, the basic functions of a class are of universal value. We can copy a class from one project to another without worrying about anything going wrong. This is because it does not have its own attribute values ​​and scopes. function group cannot do this.

One issue that needs to be clarified here is that many people mistakenly believe that dividing a function library into multiple functions will speed up program execution. Their understanding is that each page only calls the function library or class that they use. , the file size is smaller and the speed is naturally faster. In fact, the actual situation is the opposite. We all know that when we use computers, the speed may be slower when opening a WORD file for the first time, but the speed will be much faster when opening it for the second time shortly after closing. This is because that WORD files and the WORD software itself are cached in memory. In the same way, no matter how big a function library is, it is cached when the page is called for the first time, and it will naturally be much faster when it is opened again. At the same time, if a page originally contains a function library, if After decomposition, it becomes necessary to include multiple files, and file seeking takes more time than loading. Therefore, even if the page is opened without caching, decomposing a function library will reduce the execution speed of the program; in addition, classes The instantiation also takes a certain amount of time. Of course, with today's computer hardware, these speed losses are completely negligible. Therefore, the development of hardware is also one of the foundations for the popularity of object-oriented programming.

So, in process-oriented programs, we will still use classes. Of course, in process-oriented programs, classes are only needed in three situations:

The project is large enough, and a function library will When it makes people faint;

When we find that a certain function we wrote is universal;

When we call a class we wrote before or an open source class published by others online.

After using simple classes, you still cannot claim that your website is object-oriented. I just added "(Part 1)" after the title of this post. That is to say, in the rest of this article, we will still only talk about the technologies that can be used in process-oriented. Of course, they are also suitable for Object-oriented. I will express my understanding of object orientation in the next post.

4. Templates

The famous smarty, even if you have never used it, you must have heard of it. I first got to know it through xoops. At that time, I only made a simple message board. Learning SMARTY can be said to have taken a lot of effort. I remember that the best SMARTY online tutorial I found at that time was Big Brother’s smarty tutorial. I finally understood it. After a while, the brothers in Joy International Village collaborated to translate the entire smarty document, but at that time, I decided to give up. Smarty, because I insist that there is no difference between {$x} and . The so-called template, include, is enough. In order to save a few letters, I use such a big thing. It's quite unworthy. Well, here is an explanation of how to use simple PHP templates that I, oh, still use sometimes today:

文件demo.php:    
48    
49    view plaincopy to clipboardprint?    
50    <?php     
51    $userName=&#39;张三&#39;;      
52    include_once &#39;templates/demo.phtml&#39;;      
53    ?>    
54    <?php    
55    $userName=&#39;张三&#39;;    
56    include_once &#39;templates/demo.phtml&#39;;    
57    ?>    
58    文件demo.phtml:    
59    
60    view plaincopy to clipboardprint?    
61    <html>      
62    ......      
63    <body>      
64    你好,<?php  echo $userName;?>      
65    </body>      
66    </html>     
67    <html>    
68    ......    
69    <body>    
70    你好,<?php  echo $userName;?>    
71    </body>    
72    </html>
Copy after login

Look, no technology is used, isn’t it just a template? For a while, every time there was a discussion on smarty in the forum, I always wanted to promote my idea. Unfortunately, people were quiet and there was no response. Until the year before last, cakephp was introduced to China. The template technology used was very similar to my idea. Soon, After that, zend launched its own framework, which also used PHP as a natural template. In the same year, smarty was no longer developed as a core sub-project of PHP. If you visit http://smarty.php.net, you can see A reminder:

76

77 Smarty is no longer a subproject of the PHP project, and has subsequently moved to its own domain: www.smarty.net

78

79 Therefore, it is absolutely necessary to separate pages and programs. , however, template technology represented by smarty is not necessary. Unless you are doing open source programs or self-service website building, there is no way to control the security of templates. Otherwise, there is no need to use templates at all.

80

81 5. Generating static pages VS caching + pseudo-static

82

83 When I first started building a website with PHP, the first CMS system I used was called 9466 article, which used the static HTML generation technology I was amazed. Although the version at that time still had many functional deficiencies, I still spent a lot of effort to modify and learn it, and posted my modifications online. The amazing thing is that I just googled "9466 "slime modified version", there are actually many websites that provide downloads. In 2006, I made a website for a company, the URL is http://www.nbssdz.com, this time I wrote the CMS from scratch, and I also used it. Generate static page technology. However, now, I no longer use this technology. Open source programs such as joomla, phpwind, discuz and zend framework have given us another technology demonstration: pseudo-static.

84

85 There are two benefits of generating static pages. One is to increase website access speed and reduce server load. The other is to optimize search engines and allow search engines to include more pages of this site. The disadvantage of static pages is, of course, "static". It sounds like nonsense, but many dynamic functions cannot be implemented on static pages, such as displaying different content according to different user permissions. Therefore, pseudo-static is becoming popular now. The function of pseudo-static, as the name suggests, is to forge static URLs for dynamic pages to attract search engine inclusion. My website http://www.10000j.com is written based on zend framework, so it naturally has pseudo-static function. Of course, by default The URL directory format is too deep and is not conducive to inclusion. I will take the time to make changes after the year. My other website work: http://czj.kiloweb.cn has optimized the directory format. You can see that the link format is Customization is very flexible. Of course, the server load of pseudo-static is not only higher than that of static pages, but also higher than that of ordinary dynamic pages. Therefore, we must use caching flexibly to improve website response speed. Even so, pseudo-static still does not have an advantage in terms of response speed.

86

87 Therefore, for traditional content publishing categories with few functional requirements and websites with overloaded servers, we can still use the technology of generating static pages, while for websites that have permissions, click counts, etc. and require long-term maintenance To increase functionality or even for websites with independent servers, pseudo-static technology should be used. After all, some functions cannot be realized by static pages. Even if some functions can be "find a way" to achieve them (such as through ajax and iframe), the time cost of "finding a way" is too high.

88

89 6. Ajax

90

91 Ajax is an exciting technology, but the inconvenience of AJAX is that the amount of code on the website has greatly increased. In a recent project, because the page used gb2312, and the load() function of the jquery framework I used only supported utf8, I had to use iframe, and then I found out - well, this is a bit magical, after using it for so many years Iframe, after using jquery for nearly two years, I discovered that iframe is actually not bad, and it allowed me to write a lot less code. In the past year or so, I have used jquery to do a lot of things that made my boss depressed: I made some special effects that customers have never asked for, just because they are technically more dazzling, which wastes a lot of time and makes people who don’t understand jquery The artist and boss have no way to modify it themselves. So, what I want to say is that ajax is a very good thing, and jquery is the first-class ajax framework. However, good things should not be abused. You should start from the actual situation and only use them when there is a need, rather than asking me what I said before. Time is like that, you have to use it if there is a need, and you have to use it if there is no need to create a need.

92

93 7. xml and json

94

95 The advantage of frequenting the forum is that you can always keep abreast of the development trends of popular technologies. For example, one day the year before last, many people suddenly started to propose using json instead of xml. I support this suggestion with both hands. In addition to improving access speed, using json will also greatly improve development efficiency. json_encode()

96 , json_decode(), just two simple functions, can easily convert PHP arrays and json directly, which is far more convenient than simplexml and dom. Therefore, most of the time, we are neither making Google's sitemap nor RSS. We are just passing values ​​to jquery. Just use json. There is no need to use xml.


The above is the content of Rethinking PHP Programming Methods (Part 1). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!




















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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles